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.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Fileupload.aspx.cs" Inherits="Fileuploaddatabase.Fileupload" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <style type="text/css">
- body{
- font-family:Arial;
- font-size:10px;
- }
-
- td,th{
-
- height:25px;
- width:100Px;
- }
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:FileUpload ID="FileUpload" runat="server" />
- <asp:Button ID="btnUpload" runat="server" Text="Upload" Onclick="Upload" />
- <hr />
- <asp:GridView ID="GridView" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
- RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
- 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("Name") %>'></asp:LinkButton>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
-
-
-
- </div>
- </form>
- </body>
- </html>
Namespaces
You will need to import the namespaces, given below.
- using System.IO;
- using System.Data;
- using System.Data.SqlClient;
- 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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Data.SqlClient;
- using System.Web.UI.WebControls;
- using System.Configuration;
- using System.IO;
-
- namespace Fileuploaddatabase
- {
- public partial class Fileupload : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGrid();
- }
- }
-
- private void BindGrid()
-
- {
- string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- cmd.CommandText = "Select Name from dbo.tblFiles";
- cmd.Connection = con;
- con.Open();
- GridView.DataSource = cmd.ExecuteReader();
- GridView.DataBind();
- con.Close();
-
- }
- }
- }
- protected void Upload(Object Sender, EventArgs e)
- {
-
- string filename = Path.GetFileName(FileUpload.PostedFile.FileName);
- string contentType = FileUpload.PostedFile.ContentType;
- using (Stream fs = FileUpload.PostedFile.InputStream)
- {
- using (BinaryReader br = new BinaryReader(fs))
- {
- byte[] bytes = br.ReadBytes((Int32)fs.Length);
- string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
- using (SqlConnection con = new SqlConnection(constr))
- {
- string query = "insert into tblFiles values (@Name,@ContentType,@Data)";
- using (SqlCommand cmd = new SqlCommand(query))
- {
- cmd.Connection = con;
- cmd.Parameters.AddWithValue("@Name", filename);
- cmd.Parameters.AddWithValue("@ContentType", contentType);
- cmd.Parameters.AddWithValue("@Data", bytes);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- }
-
-
- }
-
- }
- Response.Redirect(Request.Url.AbsoluteUri);
-
- }
- protected void DownloadFile(object sender, EventArgs e)
- {
- int Name = 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,ContentType,Data from tblFiles where Name=@Name";
- cmd.Parameters.AddWithValue("@Name", Name);
- cmd.Connection = con;
- con.Open();
- using (SqlDataReader str = cmd.ExecuteReader())
- {
- str.Read();
- bytes = (byte[])str["Data"];
- contentType = str["contentType"].ToString();
- filename = str["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();
-
- }
- }
- }
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.