How to Upload and Download Files in to Database in Binary Format using C# and Asp.net

Introduction :

Here i will explain how to upload and Download Files into Database in Binary format. Firstly i will upload the File using Fileupload Control and displays the uploaded File in the GridView the download link in the each row is used to download the File. Here i used a 'upload' table name of Datatbase ,the database structure Shown below.

Aspx code :


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="UploadAndDownload.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
 
</head>
<body>
<form id="form1" runat="server">

<div style="text-align:center">
<asp:FileUpload ID="upload" runat="server" />
<asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click" />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"  SortExpression="ID" />
<asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" />
<asp:BoundField DataField="FileType" HeaderText="FileType" SortExpression="FileType" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" CommandArgument='<%#Bind("ID")%>'                     OnClick="download"></asp:LinkButton>
</ItemTemplate>                                                        </asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


C# code : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;

namespace UploadAndDownload
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Your Connection String");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
private void BindGridviewData() //Binding data into Grid
{
SqlCommand cmd = new SqlCommand("select * from upload", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
//uploading the File
protected void btnupload_Click(object sender, EventArgs e)
{
con.Open();
string filename = Path.GetFileName(upload.PostedFile.FileName);
string filetype = upload.PostedFile.ContentType;
Stream strm = upload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(strm);
Byte[] size = br.ReadBytes((int)strm.Length);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into upload(FileName,FileType,FileData) values(@Name,@Type,@Data)";
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@Type", filetype);
cmd.Parameters.AddWithValue("@Data", size);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
//Downloading the File
protected void download(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("select FileName, FileType, FileData from upload where Id=@id", con);
cmd.Parameters.AddWithValue("@id",((LinkButton)sender).CommandArgument);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["FileName"] + "\"");
Response.BinaryWrite((byte[])dr["FileData"]);
Response.End();
}
con.Close();
}
}
}