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.
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.
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
<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> |
using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Web.UI.WebControls; |
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(); } |
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 | |
![]() |
|
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 Email
|
|||
|
|


Subscribe by RSS
Subscribe by Email
54 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