21 November 2012

Uploading Files and Images into DB in Asp.Net


Description: 

In many websites we will see download link whenever we click on that we will have a chance to download that files into our system. 

Generally we have different ways to save files like directly in our database or our project folder. If we save files in our database it will occupy more space so it will create problem for us after host website because host providers will provide limited space for us we can solve this problem by saving files in our project folder.
Here I am going to use another post how to insert images in folder and display images from folder to implement concept like save files in folder and download those files from file system using asp.net.
To implement this first design table in your database like below to save file details in database.
Column Name
Data Type
Allow Nulls
Id
int(set identity property=true)
No
FileName
varchar(50)
Yes
FilePath
varchar(50)
Yes

Now create new website after that right click on your website and add new folder and give name as Filesbecause here I am using same name for my sample if you want to change folder name you need to change the Files folder name in your code behind also
After that design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Save and Download Files from file system</title>
<style type="text/css">
.modalBackground
{
background-colorGray;
filteralpha(opacity=80);
opacity0.8;
z-index10000;
}

.GridviewDiv {font-size100%font-family'Lucida Grande'
, 'Lucida Sans Unicode', Verdana, Arial,Helevetica, sans-serifcolor#303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em0.5em;}
.Gridview tr{colorBlackbackground-colorWhitetext-align:left}
:link,:visited { color#DF4F13text-decoration:none }

</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</div>
<div>
<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server" 
AutoGenerateColumns="false"
DataKeyNames="FilePath">
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
After completion of aspx page design add the following namespaces in code behind

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
After that write the following code in code behind


private SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridviewData();
}
}
// Bind Gridview Data
private void BindGridviewData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from FilesTable",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
// Save files to Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/"+filename));
con.Open();
SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)",con);
cmd.Parameters.AddWithValue("@Name",filename );
cmd.Parameters.AddWithValue("@Path""Files/"+filename );
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
// This button click event is used to download files from gridview
protected void lnkDownload_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
string filePath = gvDetails.DataKeys[gvrow.RowIndex].Value.ToString();
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition""attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
}
VB.NET Code

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls

Partial Class Default
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub

' Bind Gridview Data
Private Sub BindGridviewData()
con.Open()
Dim cmd As New SqlCommand("select * from FilesTable", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
gvDetails.DataSource = ds
gvDetails.DataBind()
End Sub

' Save files to Folder and files path in database
Protected Sub btnUpload_Click(ByVal sender As ObjectByVal e As EventArgs)
Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
fileUpload1.SaveAs(Server.MapPath("Files/" & filename))
con.Open()
Dim cmd As New SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con)
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@Path""Files/" & filename)
cmd.ExecuteNonQuery()
con.Close()
BindGridviewData()
End Sub

' This button click event is used to download files from gridview
Protected Sub lnkDownload_Click(ByVal sender As ObjectByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim filePath As String = gvDetails.DataKeys(gvrow.RowIndex).Value.ToString()
Response.ContentType = "image/jpg"
Response.AddHeader("Content-Disposition""attachment;filename=""" & filePath & """")
Response.TransmitFile(Server.MapPath(filePath))
Response.[End]()
End Sub
End Class


Demo