Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

save/upload files in folder and download files from folder in asp.net

Feb 27, 2012
Introduction:

In this article I will explain how to save/upload files in folder and download files from folder system when click on link in gridview using 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 Files because 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-color: Gray;
filter: alpha(opacity=80);
opacity: 0.8;
z-index: 10000;
}

.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-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 Object, ByVal 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 Object, ByVal 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 Object, ByVal 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

Download sample code attached

 

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

54 comments :

Anonymous said...

Nice aritcal .......it is very useful to me ..Thanks..

karthic said...

super website

Anonymous said...

nice sir
you are great

Anonymous said...

Great Suresh!!!

Sunil said...

how to upload the file on ftp server and retrieve,i mean show the file in gridview with remove and download button.
please help me...

Anonymous said...

This site are very good.......it's very help full.
thanks Mr. suresh dasari

your reg red by
shamsul huda

Anonymous said...

wonderful sir

you are star

you need to make big photo of your in website

Bhaskar said...

good post .

Thanks ,
bhaskar
http://csharpektroncmssql.blogpsot.com

suresh gupta said...

very nice article specially those who are beginner.

muthu said...

When i upload into hosting it is not working . how to resolve this issue.please help me

Anonymous said...

sdfdf

jagan said...

its good for all asp .net viewers and also for beginners....

Harsh Tripathi said...

Hey Suresh,
Harsh here, Ur code is good and its very helpful. I wud suggest not to use the project folder directly, instead U can create a folder on the server and ther U can upload files, directly uploading in the project folder can lead to hacking...:-)

Suresh Dasari said...

@muthu...
i think that problem is because of path to folder please change the path to your hosting provider server path...

Anonymous said...

nice site for beginners

satish said...

hi...
suresh garu..
me articles really very useful in realtime..sir..
thanks...

Anonymous said...

You have to allow nulls in your table for the ID or it may not work.

Joharika said...

Hi suresh,

If user click the save button in download save dialog box,i want to update the database with downloaded time,can u please help me.

cherry said...

it is working gud....but when uploading large files throwing ERROR...?

Anonymous said...

i faced exception in linkbtn coding .

Suresh Dasari said...

@Cherry...
To solve that error you need to increase the upload size of your files in web.config check this article
http://www.aspdotnet-suresh.com/2010/12/how-to-restrict-size-of-upload-file-in.html

bojjireddy dharmareddy said...

thank u for valuable information sharing with us

Anonymous said...

Nice work boss

Anonymous said...

really useful sort thanx.....

Anonymous said...

hi suresh....tis s bargava,ur blog is really nice and useful,and can u send me the code of upload and download the file such as,msword,pdf into sql datbase ,without using gridview....am hoping to get a reply soon...

Anonymous said...

i want to know how to scroll news headlines in ovrewebsite

Narmi Raja said...

Hi good job ........

i need one help how upload image postgres sql database using vb.net ....

Jaime Ballesteros Saravia said...

Gracias, tu ejemplo es muy claro y sencillo, justo lo que uno busca, me ayudo mucho.
Now, I'm working with telerik asp.net ajax controls if you know, please, i need help. thanks

Anonymous said...

thanks very well, thank you. really appreciate it.

Anonymous said...

Very useful. I needed to serve invoices to my customers in pdf and xlm files and thanks to your sharing I am done! Regards!

Anonymous said...

string filePath = dgvfiledown.DataKeys[gvrow.RowIndex].Value.ToString();


i got an error in this line .
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

Anonymous said...

Please help me to the post 31 ...

Hemraj Janwa said...

My best visit.....best website..its very useful for new programmer...as learner. Thanks a lot to Developer.

Kalim.Paracha said...

hi suresh....
i have some problem to use this code
if you some kind of information how to use this code in layered architecture. you know layered work very different..plz tell us some idea ....

Anonymous said...

hanks very well, thank you. really appreciate it.

Anonymous said...

we use this code than files not save in file folder in project and saved to datbase correctley plz help me

Anonymous said...

Hi sir,

I need help from your side.

If I am upload my resume means to specific fields to fetch the textbox control. for eg: email, firstname, lastname, role, mobile no to get values for to upload the resume to automatically to bind the text box control.

I need coding path and examples
please help me sir

Ashok Sahu said...

great brother your coding always help me..thanks a lot....

Anonymous said...

Hello sir give me some application of wcf

Anonymous said...

Thanks a lot .......this article was very helpful

Anonymous said...

thank u very much

Anonymous said...

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
i'm getting error like this..please help me

Water said...

Sir, I have error in downloading the file after uploading. Pls help me with this.

swornalatha said...

Sir,i want to scan the virus when uploading the files .. pls tell c# code..pls help me sir..

Anonymous said...

if i dont want to use grid view then can i download multiple files?

Johann said...

Hi. Great post. Works a charm.
I was however wondering if it is possible to save files to e.g. Dropbox or Azure cloud or Amazon or any other hosting using your steps? Or how about FTP?
How would you incorporate a username and password?

manikandan a said...

how to download sever side file through the gridview in asp.net

fungus said...

Server.MapPath is used to translate a virtual path (web path).
I want to upload file in different drive example D:/UploadFolder/ its physical path.
is there any way to upload and download file from physical path not from virtual path

Gayathri N said...

Thank you very nice article

chetan patel said...

what should be the value of date,size & type in parameters ??

chetan patel said...

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
i'm getting error like this..please help me

Darshan Kshirasagar said...

Amazing code thnx for this....:)

Anonymous said...

Hi, very nice code, I have an issue with gvDetails and FileUpload1 ..
error /// The name 'gvDetails' does not exist in the current context any help

syed irfan said...

Thanks dude...ITS WRORKING

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.