AspnetO

We code, that works!

  • Home
  • Asp.net
  • MVC
  • Interview Questions
You are here: Home / Asp.net / Upload File to Server Folder for Download in Asp.net using C# Vb.net

Upload File to Server Folder for Download in Asp.net using C# Vb.net

By: Mayank Modi | Falls In: Asp.net, C#, VB | Last Updated: Aug 18, 2014

In my previous tutorials, I’d explained about get files list from directory, how to bind data to gridview, insert update delete gridview data using parameterized query, difference between executereader executenonquery and executescalar and other more cracking tutorials on Files, Asp.net, GridView, jQuery here.

Now here in this tutorial, I’ll explain how to upload the files from your local computer and save it to server folder and then download that files from server folder in asp.net using c# and vb.net with sample demo and example code.

There are lots of plug-ins are available in the market to upload files using jQuery and JavaScript. In that some plug-ins are free and some are premium. I’ll cover that in my later posts but here I’ll explain you how to upload files and save file full path to sql server table for download from gridview using asp.net fileupload control. We need to save path to sql server because later it will be required to get the uploaded files for the download.

To save the file details to sql server we need one table. To create table in your database use this script:

CREATE TABLE [dbo].[FileDetails]
(
[FileId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[FileName] [nvarchar](50) NULL,
[FileSize] [nvarchar](50) NULL,
[FileExtension] [nvarchar](20) NULL,
[FilePath] [nvarchar](500) NULL
)

After creating database table, check the following HTML Markup and Code-behind code snippets that I prepared for the demonstration.

HTML Markup [.aspx]

Following is the complete HTML Markup code for file upload control of .aspx page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
       <title>Upload and Download files in Asp.net</title>
</head>
<body>
       <form id="form1" runat="server">
       <div>
               <table>
                       <tr>
                               <td>
                                       <asp:FileUpload ID="fuFileUploader" runat="server" />
                               </td>
                               <td>&nbsp;</td>
                               <td>
                                       <asp:Button ID="btnUploadFiles" runat="server" Text="Upload Me!"
                                       OnClick="btnUploadMe_Click" />
                               </td>
                       </tr>
                       <tr>
                               <td colspan="3">&nbsp;</td>
                       </tr>
                       <tr>
                               <td colspan="3">
                                       <asp:GridView ID="gvUploadedFiles" runat="server" AutoGenerateColumns="false"
                                       DataKeyNames="FileId">
                                           <HeaderStyle Font-Bold="true" BackColor="#ff6600" BorderColor="#f5f5f5"
                                           ForeColor="White" Height="30" />
                                           <Columns>
                                               <asp:BoundField DataField="FileId" HeaderText="#" ControlStyle-Width="50" />
                                               <asp:BoundField DataField="FileName" HeaderText="FileName"
                                               ControlStyle-Width="250" />
                                               <asp:BoundField DataField="FileSize" HeaderText="FileSize"
                                               ControlStyle-Width="250" />
                                               <asp:TemplateField>
                                                       <ItemTemplate>
                                                               <asp:LinkButton ID="lnkDownloadMe" runat="server" Text="Download Me!"
                                                               OnClick="lnkDownloadMe_Click" />
                                                       </ItemTemplate>
                                               </asp:TemplateField>
                                           </Columns>
                                       </asp:GridView>
                               </td>
                       </tr>
                       <tr>
                               <td colspan="3">&nbsp;</td>
                       </tr>
                       <tr>
                               <td>
                                       <asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>
                               </td>
                       </tr>
               </table>
       </div>
       </form>
</body>
</html>
Note: In this tutorial, I’d not validate file extension during uploading files to server. If you want to validate file extensions before uploading files, check how to validate file extension before upload and preview image before uploading here.

After adding HTML Markup code in your .aspx page, check the below code-behind code in your project language.

File Upload And Download From Gridview Example – [C#]

First add the following namespace:

//specify your connection string here..
string strConn = "Data Source=datasource;Integrated Security=true;Initial Catalog=yourDB";
protected void Page_Load(object sender, EventArgs e)
{
       lblMsg.Text = "";
       if (!IsPostBack)
       {
               BindGridviewFileData();
       }
}

//save file details to database as well as server folder
protected void btnUploadMe_Click(object sender, EventArgs e)
{
       try
       {
               if (fuFileUploader.PostedFile != null && fuFileUploader.PostedFile.ContentLength > 0)
               {
                       string fileName = Path.GetFileName(fuFileUploader.PostedFile.FileName);
                       string fileExtension = Path.GetExtension(fuFileUploader.PostedFile.FileName);

                       //first check if "uploads" folder exist or not, if not create it
                       string fileSavePath = Server.MapPath("uploads");
                       if (!Directory.Exists(fileSavePath))
                               Directory.CreateDirectory(fileSavePath);

                       //after checking or creating folder it's time to save the file
                       fileSavePath = fileSavePath + "//" + fileName;
                       fuFileUploader.PostedFile.SaveAs(fileSavePath);
                       FileInfo fileInfo = new FileInfo(fileSavePath);
                       using (SqlConnection sqlConn = new SqlConnection(strConn))
                       {
                               using (SqlCommand sqlCmd = new SqlCommand())
                               {
                                       sqlCmd.CommandText = @"INSERT INTO FileDetails
                                       (FileName,FileSize,FileExtension,FilePath)
                                       VALUES (@FileName,@FileSize,@FileExtension,@FilePath);";
                                       sqlCmd.Parameters.AddWithValue("@FileName", fileName);
                                       sqlCmd.Parameters.AddWithValue("@FileSize", fileInfo.Length.ToString());
                                       sqlCmd.Parameters.AddWithValue("@FileExtension", fileExtension);
                                       sqlCmd.Parameters.AddWithValue("@FilePath", fileSavePath);
                                       sqlCmd.Connection = sqlConn;
                                       sqlConn.Open();
                                       sqlCmd.ExecuteNonQuery();
                                       sqlConn.Close();
                                       BindGridviewFileData();
                               }
                       }

                       lblMsg.Text = "File Uploaded Successfully!";
                       lblMsg.ForeColor = System.Drawing.Color.Green;
               }
               else
               {
                       lblMsg.Text = "Error: Please select a file to upload!";
               }
       }
       catch
       {
               lblMsg.Text = "Error: Error while uploading file!";
       }
}

//download button to download files from gridview
protected void lnkDownloadMe_Click(object sender, EventArgs e)
{
       try
       {
               LinkButton lnkbtn = sender as LinkButton;
               GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
               int fileId = Convert.ToInt32(gvUploadedFiles.DataKeys[gvrow.RowIndex].Value.ToString());
               using (SqlConnection sqlConn = new SqlConnection(strConn))
               {
                       using (SqlCommand sqlCmd = new SqlCommand())
                       {
                               sqlCmd.CommandText = "SELECT * FROM FileDetails WHERE FileId=@FileId";
                               sqlCmd.Parameters.AddWithValue("@FileId", fileId);
                               sqlCmd.Connection = sqlConn;
                               sqlConn.Open();
                               SqlDataReader dr = sqlCmd.ExecuteReader();
                               if (dr.Read())
                               {
                                       string fileName = dr["FileName"].ToString();
                                       string fileLength = dr["FileSize"].ToString();
                                       string filePath = dr["FilePath"].ToString();
                                       if (File.Exists(filePath))
                                       {
                                               Response.Clear();
                                               Response.BufferOutput = false;
                                               Response.ContentType = "application/octet-stream";
                                               Response.AddHeader("Content-Length", fileLength);
                                               Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                                               Response.TransmitFile(filePath);
                                               Response.Flush();
                                       }
                                       else
                                       {
                                               lblMsg.Text = "Error: File not found!";
                                       }
                               }
                       }
               }
       }
       catch
       {
               lblMsg.Text = "Error: Error while downloading file!";
       }
}

//bind file details to gridview
private void BindGridviewFileData()
{
       try
       {
               using (SqlConnection sqlConn = new SqlConnection(strConn))
               {
                       using (SqlCommand sqlCmd = new SqlCommand())
                       {
                               sqlCmd.CommandText = "SELECT * FROM FileDetails";
                               sqlCmd.Connection = sqlConn;
                               sqlConn.Open();
                               gvUploadedFiles.DataSource = sqlCmd.ExecuteReader();
                               gvUploadedFiles.DataBind();
                               sqlConn.Close();
                       }
               }
       }
       catch { }
}

File Upload And Download From Gridview Example – [Vb.net]

First add the following namespace:

Imports System.Data.SqlClient
Imports System.IO

Now add the below sample code snippet to perform upload and download files from server folder:

'specify your connection string here..
Dim strConn As String = "Data Source=datasource;Integrated Security=true;Initial Catalog=yourDB"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
       lblMsg.Text = ""
       If Not IsPostBack Then
               BindGridviewFileData()
       End If
End Sub

'save file details to database as well as server folder
Protected Sub btnUploadMe_Click(ByVal sender As Object, ByVal e As EventArgs)
       Try
               If fuFileUploader.PostedFile IsNot Nothing Then
                       Dim fileName As String = Path.GetFileName(fuFileUploader.PostedFile.FileName)
                       Dim fileExtension As String = Path.GetExtension(fuFileUploader.PostedFile.FileName)

                       'first check if "uploads" folder exist or not, if not create it
                       Dim fileSavePath As String = Server.MapPath("uploads")
                       If Not Directory.Exists(fileSavePath) Then
                               Directory.CreateDirectory(fileSavePath)
                       End If

                       'after checking or creating folder it's time to save the file
                       fileSavePath = fileSavePath & "//" & fileName
                       fuFileUploader.PostedFile.SaveAs(fileSavePath)
                       Dim fileInfo As New FileInfo(fileSavePath)
                       Using sqlConn As New SqlConnection(strConn)
                               Using sqlCmd As New SqlCommand()
                                       sqlCmd.CommandText = "INSERT INTO FileDetails" & ControlChars.CrLf & _
                                       "(FileName,FileSize,FileExtension,FilePath) " & ControlChars.CrLf & _
                                       "VALUES (@FileName,@FileSize,@FileExtension,@FilePath);"
                                       sqlCmd.Parameters.AddWithValue("@FileName", fileName)
                                       sqlCmd.Parameters.AddWithValue("@FileSize", fileInfo.Length.ToString())
                                       sqlCmd.Parameters.AddWithValue("@FileExtension", fileExtension)
                                       sqlCmd.Parameters.AddWithValue("@FilePath", fileSavePath)
                                       sqlCmd.Connection = sqlConn
                                       sqlConn.Open()
                                       sqlCmd.ExecuteNonQuery()
                                       sqlConn.Close()
                                       BindGridviewFileData()
                               End Using
                       End Using

                       lblMsg.Text = "File Uploaded Successfully!"
                       lblMsg.ForeColor = System.Drawing.Color.Green
               Else
                       lblMsg.Text = "Error: Please select a file to upload!"
               End If
       Catch
               lblMsg.Text = "Error: Error while uploading file!"
       End Try
End Sub

'download button to download files from gridview
Protected Sub lnkDownloadMe_Click(ByVal sender As Object, ByVal e As EventArgs)
       Try
               Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
               Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
               Dim fileId As Integer =
               Convert.ToInt32(gvUploadedFiles.DataKeys(gvrow.RowIndex).Value.ToString())
               Using sqlConn As New SqlConnection(strConn)
                       Using sqlCmd As New SqlCommand()
                               sqlCmd.CommandText = "SELECT * FROM FileDetails WHERE FileId=@FileId"
                               sqlCmd.Parameters.AddWithValue("@FileId", fileId)
                               sqlCmd.Connection = sqlConn
                               sqlConn.Open()
                               Dim dr As SqlDataReader = sqlCmd.ExecuteReader()
                               If dr.Read() Then
                                       Dim fileName As String = dr("FileName").ToString()
                                       Dim fileLength As String = dr("FileSize").ToString()
                                       Dim filePath As String = dr("FilePath").ToString()
                                       If File.Exists(filePath) Then
                                               Response.Clear()
                                               Response.BufferOutput = False
                                               Response.ContentType = "application/octet-stream"
                                               Response.AddHeader("Content-Length", fileLength)
                                               Response.AddHeader("content-disposition", "attachment; filename=" & fileName)
                                               Response.TransmitFile(filePath)
                                               Response.Flush()
                                       Else
                                               lblMsg.Text = "Error: File not found!"
                                       End If
                               End If
                       End Using
               End Using
       Catch
               lblMsg.Text = "Error: Error while downloading file!"
       End Try
End Sub

'bind file details to gridview
Private Sub BindGridviewFileData()
       Try
               Using sqlConn As New SqlConnection(strConn)
                       Using sqlCmd As New SqlCommand()
                               sqlCmd.CommandText = "SELECT * FROM FileDetails"
                               sqlCmd.Connection = sqlConn
                               sqlConn.Open()
                               gvUploadedFiles.DataSource = sqlCmd.ExecuteReader()
                               gvUploadedFiles.DataBind()
                               sqlConn.Close()
                       End Using
               End Using
       Catch
       End Try
End Sub

Example Result

How to upload files to server folder for download in asp.net c# vb.net?

Download Example

Icon

How to upload and download files from server folder in asp.net?

1 file(s) 78.08 KB
Download This Example

Signup Today And Get Latest Tutorials For Free!

Subscribe to us and get free latest tutorials notifications whenever we publish a new contents.

<

About Mayank Modi

Mayank is a web developer and designer who specializes in back-end as well as front-end development. He's a Founder & Chief Editor of AspnetO. If you'd like to connect with him, follow him on Twitter as @immayankmodi.

Search Your Topic



Social Connections

  • 1,438 Fans
  • 3,098 Followers
  • 51 Followers
  • 1,559 Subscribers

Get Latest Tutorials For Free



Top Posts

  • CSS3 Transition: fadeIn and fadeOut like Effects to Hide Show Elements
  • Top 10 OOPS Concepts In C# .NET With Examples
  • Show Confirm Message Box from Code-behind in Asp.net
  • Call JavaScript Function from Code-behind in Asp.net C# Vb
  • Pass Multiple Parameters in Asp.net QueryString Example

Contribute to AspnetO

If you want to contribute your unique blog articles or tutorials (Free / Paid) to AspnetO in any languages, you're most welcome. Just send me your previous articles, and topics on which you are interested to post an tutorial. Contact us at email listed in contact us page. Selected candidates will be contacted.

Search by Tags

Ado.net Ajax appSettings Asp.net C# CheckBox CheckBoxList ConnectionStrings Control CSS CSS3 Difference Download DropDownList Export Facebook fadeIn fadeOut fadeTo fadeToggle File File Extension FileUpload Function GridView IIS Interview Questions JavaScript jQuery MVC OOP RadioButtonList RDP Repeater Send Mail Solutions Split SQL Stored Procedure TextBox Upload Validation VB Web.config Web Hosting

The Man Behind AspnetO

Mayank Modi

Hi there,

Myself Mayank Modi, a Full Stack Developer (.NET Stack) and a blogger from Surat, India.

I'm welcoming you to my blog - AspnetO, a programmers community blog where we code, that works!

I started AspnetO as a hobby and now we're growing day by day. We're now having 5000+ programmers that get benefits and learn new things about website design and development under our community blog.

Here at AspnetO, I write about Beginners to Advance level of tutorials on programming languages like Asp.net using C# and Vb.net, MVC, SQL Server, JavaScript, jQuery etc. In sort, all about .NET Framework and website development stuff and sometimes sharing tips and tricks that can help you to grow up your programming skills.

You can get more details about me and my blog at About us page.

Subscribe To Newsletter

Enter your email address to subscribe to this blog and receive notifications of new posts right to your inbox

Join 1000+ other subscribers

<

Recent Posts

  • Main Difference between SessionState and ViewState in Asp.net
  • How to Get appSettings Value from Web.config File?
  • How to Get ConnectionString from Web.config in Asp.net?
  • Difference between appSettings and connectionStrings in Web.config
  • Get Folder Files List and Export to CSV in .NET
  • Get Files List From Directory Recursively in C# Vb.net
  • Get Hash Value From Current Page URL In jQuery
  • Handle Multiple Submit Buttons in Single MVC Form

Copyright © 2014 - 2021 · All Rights Reserved.

About | Copyrights | Privacy | Terms | Contact | Advertise | Sitemap
Previous CheckBoxList Validation: CheckBoxList Validation using jQuery in Asp.net
Next Validate File Extension During File Upload using JavaScript in Asp.net