In this article I will explain with an example, how to display files saved in
SQL Server Database Table in
ASP.Net using C# and VB.Net.
The files will be displayed in the
ASP.Net GridView with Download
LinkButton button, to download the file from database in
ASP.Net.
Database
I have made use of the following table tblFiles with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Download SQL file
HTML Markup
The
HTML Markup consists of:
GridView - For displaying data.
The
GridView consists of a
BoundField column and a
TemplateField column.
BoundField - For displaying the Name of the File.
TemplateField – The TemplateField column consists of ItemTemplate column.
ItemTemplate - For displaying Download LinkButton.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="File Name" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("Id")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Displaying the uploaded files from Database Table in ASP.Net GridView
Inside the
Page Load event, the
BindGrid method is called and the
GridView is populated with the records i.e. Files from the
SQL Server Database Table.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Id, Name FROM tblFiles";
cmd.Connection = con;
con.Open();
gvCustomers.DataSource = cmd.ExecuteReader();
gvCustomers.DataBind();
con.Close();
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Id, Name FROM tblFiles"
cmd.Connection = con
con.Open()
gvCustomers.DataSource = cmd.ExecuteReader()
gvCustomers.DataBind()
con.Close()
End Using
End Using
End Sub
Downloading File from Database Table
When the Download LinkButton is clicked, first the File ID of the file to be downloaded is fetched using the CommandArgument property of the LinkButton.
The details of the File such as Name, Content Type and the File in Byte Array are fetched from the database using
SqlDataReader.
Then, the Response class properties are set.
Properties:
1.
ContentType – It informs the Browser about the file type. In this case it is
PDF.
2. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
Finally, using the BinaryWrite method of the Response class inside which Byte Array is passed as parameter, the File is written to the Response Stream using its Path and File is downloaded.
C#
protected void DownloadFile(object sender ,EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
VB.Net
Protected Sub DownloadFile(sender As Object, e As EventArgs)
Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
Dim bytes As Byte()
Dim fileName As String, contentType As String
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id"
cmd.Parameters.AddWithValue("@Id", id)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
bytes = DirectCast(sdr("Data"), Byte())
contentType = sdr("ContentType").ToString()
fileName = sdr("Name").ToString()
End Using
con.Close()
End Using
End Using
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = contentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName)
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
Screenshot
Downloads