Upload and Download File Using GridView and SQL Server 2008

In an ASP.NET project we need to upload and download files. For that I am using SQL Server and a GridView. The GridView shows that list of uploaded files with the file name and file type and provide the Download link for each file.

Use the following the procedure.

Open Visual Studio 2008 then select "File" -> "New" -> "Project...".

Asp empty website

Create a database table named “FileInformation”.

Database table

Design and Coding

Design

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <script type="text/javascript">  
  5.         function myfunction() {  
  6.             alert("Please Upload File");  
  7.         }  
  8.     </script>  
  9. </head>  
  10. <body>  
  11.     <form id="form1" runat="server">  
  12.     <div>  
  13.         <asp:FileUpload ID="fileUpload1" runat="server" /><br />  
  14.         <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />  
  15.     </div>  
  16.     <div>  
  17.         <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" DataKeyNames="Id">  
  18.             <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />  
  19.             <Columns>  
  20.                 <asp:BoundField DataField="Id" HeaderText="Id" />  
  21.                 <asp:BoundField DataField="FileName" HeaderText="FileName" />  
  22.                 <asp:TemplateField HeaderText="FilePath">  
  23.                     <ItemTemplate>  
  24.                         <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>  
  25.                     </ItemTemplate>  
  26.                 </asp:TemplateField>  
  27.             </Columns>  
  28.         </asp:GridView>  
  29.     </div>  
  30.     </form>  
  31. </body>  
  32. </html>  
Code 
  1. string strCon = "Data Source=(local);Integrated Security=true;Initial Catalog=Test";  
  2.         protected void Page_Load(object sender, EventArgs e)  
  3.         {  
  4.             if (!IsPostBack)  
  5.             {  
  6.                 BindGridviewData();  
  7.             }  
  8.         }  
  9.   
  10.         // Bind Gridview Data  
  11.         private void BindGridviewData()  
  12.         {  
  13.             using (SqlConnection con = new SqlConnection(strCon))  
  14.             {  
  15.                 using (SqlCommand cmd = new SqlCommand())  
  16.                 {  
  17.                     cmd.CommandText = "select * from FileInformation";  
  18.                     cmd.Connection = con;  
  19.                     con.Open();  
  20.                     gvDetails.DataSource = cmd.ExecuteReader();  
  21.                     gvDetails.DataBind();  
  22.                     con.Close();  
  23.                 }  
  24.             }  
  25.         }  
  26.         protected void btnUpload_Click(object sender, EventArgs e)  
  27.         {  
  28.             if (fileUpload1.HasFile)  
  29.             {  
  30.                 string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);  
  31.                 Stream str = fileUpload1.PostedFile.InputStream;  
  32.                 BinaryReader br = new BinaryReader(str);  
  33.                 Byte[] size = br.ReadBytes((int)str.Length);  
  34.                 using (SqlConnection con = new SqlConnection(strCon))  
  35.                 {  
  36.                     using (SqlCommand cmd = new SqlCommand())  
  37.                     {  
  38.                         cmd.CommandText = "insert into FileInformation(FileName,FileType,FileData) values(@Name,@Type,@Data)";  
  39.                         cmd.Parameters.AddWithValue("@Name", filename);  
  40.                         cmd.Parameters.AddWithValue("@Type""application/word");  
  41.                         cmd.Parameters.AddWithValue("@Data", size);  
  42.                         cmd.Connection = con;  
  43.                         con.Open();  
  44.                         cmd.ExecuteNonQuery();  
  45.                         con.Close();  
  46.                         BindGridviewData();  
  47.                     }  
  48.                 }  
  49.             }  
  50.             else  
  51.             {  
  52.                 ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage""myfunction();"true);  
  53.             }  
  54.         }  
  55.   
  56.         // This button click event is used to download files from gridview  
  57.         protected void lnkDownload_Click(object sender, EventArgs e)  
  58.         {  
  59.             LinkButton lnkbtn = sender as LinkButton;  
  60.             GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;  
  61.             int fileid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value.ToString());  
  62.             string name, type;  
  63.             using (SqlConnection con = new SqlConnection(strCon))  
  64.             {  
  65.                 using (SqlCommand cmd = new SqlCommand())  
  66.                 {  
  67.                     cmd.CommandText = "select FileName, FileType, FileData from FileInformation where Id=@Id";  
  68.                     cmd.Parameters.AddWithValue("@id", fileid);  
  69.                     cmd.Connection = con;  
  70.                     con.Open();  
  71.                     SqlDataReader dr = cmd.ExecuteReader();  
  72.                     if (dr.Read())  
  73.                     {  
  74.                         Response.ContentType = dr["FileType"].ToString();  
  75.                         Response.AddHeader("Content-Disposition",   
  76.                                             "attachment;filename=\"" + dr["FileName"] + "\"");  
  77.                         Response.BinaryWrite((byte[])dr["FileData"]);  
  78.                         Response.End();  
  79.                     }  
  80.                 }  
  81.             }  
  82.         }  
  83.     }  

Up Next
    Ebook Download
    View all
    Learn
    View all