Hi kranthivar,
I have created sample that fullfill your requirement by refering the below articles.
HTML
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text="" Font-Names="Arial"></asp:Label>
<br />
<asp:GridView runat="server" ID="gvFiles" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" OnClick="Download" CommandArgument='<%# Eval("Id") %>'>Download</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strQuery = "SELECT Id,Name FROM tblFiles";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
gvFiles.DataSource = dt;
gvFiles.DataBind();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string extension = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (extension.ToLower())
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "INSERT INTO tblFiles(Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
Save(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats";
}
}
protected void Download(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
string strQuery = "SELECT Name, ContentType, Data FROM tblFiles WHERE Id = @Id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@Id", id);
DataTable dt = GetData(cmd);
if (dt != null && dt.Rows.Count > 0)
{
string name = dt.Rows[0]["Name"].ToString();
string contentType = dt.Rows[0]["ContentType"].ToString();
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AddHeader("content-disposition", "attachment;filename=" + name);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
private Boolean Save(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim strQuery As String = "SELECT Id,Name FROM tblFiles"
Dim cmd As New SqlCommand(strQuery)
Dim dt As DataTable = GetData(cmd)
gvFiles.DataSource = dt
gvFiles.DataBind()
End If
End Sub
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim extension As String = Path.GetExtension(filename)
Dim contenttype As String = [String].Empty
Select Case extension.ToLower()
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> [String].Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
'insert the file into database
Dim strQuery As String = "INSERT INTO tblFiles(Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
Save(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"
End If
End Sub
Protected Sub Download(sender As Object, e As EventArgs)
Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
Dim strQuery As String = "SELECT Name, ContentType, Data FROM tblFiles WHERE Id = @Id"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("@Id", id)
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
Dim name As String = dt.Rows(0)("Name").ToString()
Dim contentType As String = dt.Rows(0)("ContentType").ToString()
Dim bytes As [Byte]() = DirectCast(dt.Rows(0)("Data"), [Byte]())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = contentType
Response.AddHeader("content-disposition", Convert.ToString("attachment;filename=") & name)
Response.BinaryWrite(bytes)
Response.Flush()
Response.[End]()
End If
End Sub
Private Function Save(cmd As SqlCommand) As [Boolean]
Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function
Private Function GetData(cmd As SqlCommand) As DataTable
Dim dt As New DataTable()
Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function