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.
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
Download sample code attached
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.
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
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. |
|||
|
|||
98 comments :
Nice aritcal .......it is very useful to me ..Thanks..
super website
nice sir
you are great
Great Suresh!!!
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...
This site are very good.......it's very help full.
thanks Mr. suresh dasari
your reg red by
shamsul huda
wonderful sir
you are star
you need to make big photo of your in website
good post .
Thanks ,
bhaskar
http://csharpektroncmssql.blogpsot.com
very nice article specially those who are beginner.
When i upload into hosting it is not working . how to resolve this issue.please help me
sdfdf
its good for all asp .net viewers and also for beginners....
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...:-)
@muthu...
i think that problem is because of path to folder please change the path to your hosting provider server path...
nice site for beginners
hi...
suresh garu..
me articles really very useful in realtime..sir..
thanks...
You have to allow nulls in your table for the ID or it may not work.
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.
it is working gud....but when uploading large files throwing ERROR...?
i faced exception in linkbtn coding .
@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
thank u for valuable information sharing with us
Nice work boss
really useful sort thanx.....
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...
i want to know how to scroll news headlines in ovrewebsite
Hi good job ........
i need one help how upload image postgres sql database using vb.net ....
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
thanks very well, thank you. really appreciate it.
Very useful. I needed to serve invoices to my customers in pdf and xlm files and thanks to your sharing I am done! Regards!
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"
Please help me to the post 31 ...
My best visit.....best website..its very useful for new programmer...as learner. Thanks a lot to Developer.
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 ....
hanks very well, thank you. really appreciate it.
we use this code than files not save in file folder in project and saved to datbase correctley plz help me
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
great brother your coding always help me..thanks a lot....
Hello sir give me some application of wcf
Thanks a lot .......this article was very helpful
thank u very much
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
Sir, I have error in downloading the file after uploading. Pls help me with this.
Sir,i want to scan the virus when uploading the files .. pls tell c# code..pls help me sir..
if i dont want to use grid view then can i download multiple files?
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?
how to download sever side file through the gridview in asp.net
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
Thank you very nice article
what should be the value of date,size & type in parameters ??
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
Amazing code thnx for this....:)
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
Thanks dude...ITS WRORKING
How To Load File Automatically into File Up loader.
I have requirement , I have asp page with file up-loader and button name "upload"...with out using the browse ,i want load some default file in file up-loader ,suppose , I have folder in c:\serverfloder and i have image "image1.jpg" in that ..when user request 1 time ,i want to automatically load the file into file up-loader ..based user requirement we give chance the change the file file ....i don't want to restrict the user.
Suresh sir ...Please help me ..... my question is how to view a uploaded document without downloading that doc...... just i need to view that doc in page itself
do we have same thing for java ?
How to delete the uploaded document sir plz help me.
how to count length of character in custom editor using asp.net
plz solve my problem sir..
All Nice aritcal .......it is very useful to me ..Thanks..
good article
sir ji i have one problem when i use download code getting some unable to valid expression
c#
hi,once i submit m resume ,it need to be saved in a folder with the name of the user along with time.can u help me in this regard
Hi suresh sir !
I'm shivangi. Your articles are really good n helpful. These articles helped me a lot in my project .
How to delete a file which has upload from datagrid? Please help
Good Post
Thanks
Bhaskar.
I create word doc dynamicaly.how to save with proper naming?
I want to do same Thing in Windows application how can i do pls reply....
Thanks
My twitter account did not registered api twitter .com/oauth/request_token. Can i update my account.
But i don't know my callback url.
Very helpful article. Only I have a problem. I used your code and my page shows all images, looks good! But except imagges it shows Thumb.db link. When I click on the link - there is nothing. There is no such db in the directory. How can I get rid of showing this link?
Please, advise.
this code is not work in internet explorer
hi..which tool u have used for live demo..
thankyou so much.........
very nice app........
thank you
code is running without any error, but not getting the download option,can any one help me pz
Hi Suresh ,
Everything is Working Fine , But i want to download file directly to "D:\\Project" without asking Open save dialogue .
Hi Suresh,
This is working fine with fileupload control and save file in a desired location. I am asking one thing, that i need to save file that came from my database in a desired location as above. can you please suggest me without fileupload control.
Good website for fresher as well as experienced..!! Keep updating Bro!!
Could not complete the operation due to error c00ce514.
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Response.TransmitFile(Server.MapPath(filePath))
Why "GridViewRow" and Response.TransmitFile undifined in asp.net 2003 / visual studio 2003...???
Hi Suresh,
I am using below code for download.
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
Upon click of the download button, i am getting Open/Save/Cancel dialog box, but i still able to click download button once again, without answering the dialog box. I wanted to open Model Dialog box. Please guide me in this.
Thanks
Priya.
Hi Suresh,
My scenerio is little bit different, I want to save and download the asp.net website in html format with running it on browser just like www.wix.com.I searched a lots but dint get any solution.Kindly tell me if you have any answer.
Regards
If its inside the Update Panel then ?
Hi suresh,
Article is very nice.
But one error is display...String or binary data would be truncated.
The statement has been terminated.
You are my god
dear sir in behind code c# with asp.net it 's ok but in vb.net when I try upload it show me object reference not
instance an object could you show me?
Can u teach file upload and download from remote server using FTP?
How can you delete the file and the line of the gridview at the same time
good
Thank U So Much..... It is Very Much Useful For Me....!
Can we hide the (download) save pop up . and gives physical path like ("E:\ABC") folder name ?
If know please tell me . thanks in advance.
thank you very much for this tutorial.
thanks very short n valuable code
hi this is jyoti.
i don't want to use fileupload control . i retrive value from the database in gridview then i want to to download
Can we upload video and audio and download??
thank u.can i know how to retriew file stored in database with varbinary.
I need this in windows form application where i browse a file and save in the folder only name of file i do save in database table.
I already upload the file and displayed in gridview now i want to download the files from grid view
Note: Only a member of this blog may post a comment.