Upload and Download Files using Asp.Net
How to upload and save 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 database.
Database
source code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="updownfiles.aspx.cs" Inherits="rememberme.updownfiles" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /><br />
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None">
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
<Columns>
<asp:TemplateField HeaderText="Download">
<ItemTemplate>
<asp:LinkButton ID="lnkView" Text = "Download" CommandArgument = '<%# Eval("Id") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="Label6" Visible="false" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
C# Code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace rememberme
{
public partial class updownfiles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("SELECT Id,FileName,FileData FROM upd_db ", con);
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
Label6.Visible = false;
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
else
{
Label6.Visible = true;
Label6.Text = "No Records Found";
}
}
}
}
}
}
protected void DownloadFile(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
int Id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string FileName;
FileName = ((sender as LinkButton).CommandArgument);
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select * from upd_db where Id=@Id";
cmd.Parameters.AddWithValue("@Id", Id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["FileData"];
FileName = sdr["FileName"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.AppendHeader("Content-Disposition", "attachment; Filename=" + FileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
protected void Button1_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string extension = Path.GetExtension(filename);
HttpPostedFile file = FileUpload1.PostedFile;
byte[] document = new byte[file.ContentLength];
file.InputStream.Read(document, 0, file.ContentLength);
//Validations
if ((extension == ".doc") || (extension == ".docx") || (extension == ".pdf"))//extension
{
if (file.ContentLength <= 31457280)//size
{
//Insert the Data in the Table
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
string commandText = @"insert into upd_db(FileName,FileData)values(@FileName,@FileData)";
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@FileName", SqlDbType.VarChar);
cmd.Parameters["@FileName"].Value = filename;
cmd.Parameters.Add("@FileData", SqlDbType.VarBinary);
cmd.Parameters["@FileData"].Value = document;
connection.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
else
{ Response.Write("Invalid File size"); return; }
}
else
{
ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Invalid File Format');</script>");
return;
}
ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('File Uploaded Successfully ');</script>");
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}