Upload File Show In Grid View, Store Database And Download Using ASP.NET And C#

In this blog, I will explain how to upload and save the files to SQL Server database table, using File Upload control and then display the saved files in ASP.NET GridView with download button to download the saved file from the database.
 
Database
  •  For this blog, I have created a simple table with the structure, given below.
  •  I have created the database, where there are three fields- Name,Content Type and Data.     
Post Screen shot My Database Table looks like,



HTML Markup

HTML Markup contains a FileUpload and a button to upload and save the files to the database and an ASP.NET GridView control to display the uploaded files and also to allow the user to download the file saved in the database. ID of the file is bound to the CommandArgument property of the LinkButton. It will be used to download the file.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Fileupload.aspx.cs" Inherits="Fileuploaddatabase.Fileupload" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <style type="text/css">  
  9.         body{  
  10.             font-family:Arial;  
  11.             font-size:10px;  
  12.         }  
  13.   
  14.         td,th{  
  15.   
  16.             height:25px;  
  17.             width:100Px;  
  18.         }  
  19.     </style>  
  20. </head>  
  21. <body>  
  22.     <form id="form1" runat="server">  
  23.     <div>  
  24.    <asp:FileUpload  ID="FileUpload"  runat="server" />  
  25.    <asp:Button ID="btnUpload" runat="server" Text="Upload" Onclick="Upload" />  
  26.     <hr />  
  27.     <asp:GridView ID="GridView" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"  
  28.             RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"  
  29.             AutoGenerateColumns="false">  
  30.          <Columns>  
  31.                 <asp:BoundField DataField="Name" HeaderText="File Name" />  
  32.                 <asp:TemplateField ItemStyle-HorizontalAlign="Center">  
  33.                     <ItemTemplate>  
  34.                         <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"  
  35.                             CommandArgument='<%# Eval("Name") %>'></asp:LinkButton>  
  36.                     </ItemTemplate>  
  37.                 </asp:TemplateField>  
  38.             </Columns>  
  39.      </asp:GridView>  
  40.   
  41.   
  42.   
  43.     </div>  
  44.     </form>  
  45. </body>  
  46. </html>  
Namespaces

You will need to import the namespaces, given below.
  1. using System.IO;  
  2. using System.Data;  
  3. using System.Data.SqlClient;  
  4. using System.Configuration;  
Display the uploaded files from the database table in ASP.NET GridView and download the file from the uploaded file. The code is given below, which populates ASP.NET GridView from the files saved in the database table.

The event handler, given below, is raised when the download LinkButton is clicked inside the GridView row. First, the ID of the file is determined, using the CommandArgument property of the LinkButton and then the file data, i.e. Name, Content Type and the Byte Array,  is retrieved from the database. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Data.SqlClient;  
  7. using System.Web.UI.WebControls;  
  8. using System.Configuration;  
  9. using System.IO;  
  10.   
  11. namespace Fileuploaddatabase  
  12. {  
  13.     public partial class Fileupload : System.Web.UI.Page  
  14.     {  
  15.         protected void Page_Load(object sender, EventArgs e)  
  16.         {  
  17.             if (!IsPostBack)  
  18.             {  
  19.                 BindGrid();  
  20.             }  
  21.         }  
  22.   
  23.         private void BindGrid()  
  24.   
  25.         {  
  26.             string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  27.             using (SqlConnection con = new SqlConnection(constr))  
  28.             {  
  29.                 using (SqlCommand cmd = new SqlCommand())  
  30.                 {  
  31.                     cmd.CommandText = "Select Name from dbo.tblFiles";  
  32.                     cmd.Connection = con;  
  33.                     con.Open();  
  34.                     GridView.DataSource = cmd.ExecuteReader();  
  35.                     GridView.DataBind();  
  36.                     con.Close();  
  37.   
  38.                 }  
  39.             }  
  40.         }  
  41.         protected void Upload(Object Sender, EventArgs e)  
  42.         {  
  43.   
  44.             string filename = Path.GetFileName(FileUpload.PostedFile.FileName);  
  45.             string contentType = FileUpload.PostedFile.ContentType;  
  46.             using (Stream fs = FileUpload.PostedFile.InputStream)  
  47.             {  
  48.                 using (BinaryReader br = new BinaryReader(fs))  
  49.                 {  
  50.                     byte[] bytes = br.ReadBytes((Int32)fs.Length);  
  51.                     string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  52.                     using (SqlConnection con = new SqlConnection(constr))  
  53.                     {  
  54.                         string query = "insert into tblFiles values (@Name,@ContentType,@Data)";  
  55.                         using (SqlCommand cmd = new SqlCommand(query))  
  56.                         {  
  57.                             cmd.Connection = con;  
  58.                             cmd.Parameters.AddWithValue("@Name", filename);  
  59.                             cmd.Parameters.AddWithValue("@ContentType", contentType);  
  60.                             cmd.Parameters.AddWithValue("@Data", bytes);  
  61.                             con.Open();  
  62.                             cmd.ExecuteNonQuery();  
  63.                             con.Close();  
  64.                         }  
  65.                     }  
  66.   
  67.   
  68.                 }  
  69.   
  70.             }  
  71.             Response.Redirect(Request.Url.AbsoluteUri);  
  72.   
  73.         }  
  74.         protected void DownloadFile(object sender, EventArgs e)  
  75.         {  
  76.             int Name = int.Parse((sender as LinkButton).CommandArgument);  
  77.             byte[] bytes;  
  78.             string filename, contentType;  
  79.             string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  80.             using (SqlConnection con = new SqlConnection(constr))  
  81.             {  
  82.                 using (SqlCommand cmd = new SqlCommand())  
  83.   
  84.                 {  
  85.   
  86.                     cmd.CommandText = "select Name,ContentType,Data from  tblFiles where Name=@Name";  
  87.                     cmd.Parameters.AddWithValue("@Name", Name);  
  88.                     cmd.Connection = con;  
  89.                     con.Open();  
  90.                     using (SqlDataReader str = cmd.ExecuteReader())  
  91.                     {  
  92.                         str.Read();  
  93.                         bytes = (byte[])str["Data"];  
  94.                         contentType = str["contentType"].ToString();  
  95.                         filename = str["Name"].ToString();  
  96.                     }  
  97.                     con.Close();  
  98.                 }  
  99.             }  
  100.             Response.Clear();  
  101.             Response.Buffer = true;  
  102.             Response.Charset = "";  
  103.             Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  104.             Response.ContentType = contentType;  
  105.             Response.AppendHeader("Content-Disposition""attachment;filename=" + filename);  
  106.             Response.BinaryWrite(bytes);  
  107.             Response.Flush();  
  108.             Response.End();  
  109.   
  110.         }  
  111.     }  
  112. }  
Finally, output will be given, as follows.


SQL output looks as follows.



Summary

I explained with an example and attached the sample code, how to upload the files to the database in ASP.NET, using FileUpload control and then download the saved or stored files from SQL Server database, using GridView control.