Uploading and Downloading a File in an ASP.NET Web Application

Problem

When we Click on a Upload File Button, it should upload the file to the physical directory and then at the same time that file info should be available in a Grid and also from grid itself we should be able to download that file.

Solution

Step 1 - Create an ASP.NET Web application and Add a Webform to it and a folder to save the uploaded file.

Step 2 - Copy the Below HTML Code which is Well Commented to Understand.

  1. <!DOCTYPE html>  
  2.   
  3. <html>  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.         <div>  
  10.             <%--ASP.NET control to upload a file--%>  
  11.             <asp:FileUpload ID="FileUpload1" runat="server" />  
  12.                
  13.             <%--Button to Upload the file--%>  
  14.             <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload File" />  
  15.             <br />  
  16.             <br />  
  17.             <br />  
  18.             <%--Gridview to Display the Available data with file Details--%>  
  19.             <%--Generate the OnRowCommand Event Handler of the Gridview Control--%>  
  20.             <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" Width="513px">  
  21.                 <AlternatingRowStyle BackColor="White" />  
  22.                 <Columns>  
  23.                     <%--Item Template is used to Add a custom link button whose Eval Binding is "File"--%>  
  24.                     <asp:TemplateField HeaderText="File Name">  
  25.                         <ItemTemplate>  
  26.                             <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("File") %>' Text='<%# Eval("File") %>'></asp:LinkButton>  
  27.                         </ItemTemplate>  
  28.                     </asp:TemplateField>  
  29.                     <asp:BoundField DataField="Size" HeaderText="Size (KB)" />  
  30.                     <asp:BoundField DataField="Type" HeaderText="File Type with Extension" />  
  31.                 </Columns>  
  32.                 <EditRowStyle BackColor="#2461BF" />  
  33.                 <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  34.                 <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  35.                 <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />  
  36.                 <RowStyle BackColor="#EFF3FB" />  
  37.                 <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />  
  38.                 <SortedAscendingCellStyle BackColor="#F5F7FB" />  
  39.                 <SortedAscendingHeaderStyle BackColor="#6D95E1" />  
  40.                 <SortedDescendingCellStyle BackColor="#E9EBEF" />  
  41.                 <SortedDescendingHeaderStyle BackColor="#4870BE" />  
  42.             </asp:GridView>  
  43.         </div>  
  44.     </form>  
  45. </body>  
  46. </html>  
Step 3 - Copy the Below C# Code to the Code behind file which is Well commented to Understand.
  1. using System;  
  2. using System.Data;  
  3. using System.IO;  
  4. using System.Web.UI.WebControls;  
  5. namespace FileUploadAndDownloadDemo  
  6. {  
  7.     public partial class Index : System.Web.UI.Page  
  8.     {  
  9.         protected void Page_Load(object sender, EventArgs e)  
  10.         {  
  11.             if (!IsPostBack) //Used to Check whether the Page is loaded first time or not  
  12.             {  
  13.                 ListOfData(); //Custom Method Called  
  14.             }  
  15.         }  
  16.         protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) //Is fired when File is Downloaded  
  17.         {  
  18.             Response.Clear();  
  19.             Response.ContentType = "application/octet-stream";  
  20.             Response.AppendHeader("Content-Disposition""filename=" + e.CommandArgument); //Used to append the filename at the time of Downloading  
  21.             Response.TransmitFile(Server.MapPath("~/MyUploads/") + e.CommandArgument); //Used to Fetch the file from the Physical folder of Server  
  22.             Response.End();  
  23.         }  
  24.         protected void Button1_Click(object sender, EventArgs e)  
  25.         {  
  26.             if (FileUpload1.HasFile) //If the used Uploaded a file  
  27.             {  
  28.                 string FileName = FileUpload1.FileName; //Name of the file is stored in local Variable  
  29.                 FileUpload1.PostedFile.SaveAs(Server.MapPath("~/MyUploads/") + FileName); //File is saved in the Physical folder  
  30.             }  
  31.             ListOfData(); //Custom method is Called  
  32.         }  
  33.         //Custom Methods used in the Above Code  
  34.         private void ListOfData()  
  35.         {  
  36.             DataTable dt = new DataTable(); //Datatable is Created to Add Dynamic Columns  
  37.             //Columns Added with the Same name as that of Eval Expression and the DataField Value of the Gridview  
  38.             dt.Columns.Add("File");  
  39.             dt.Columns.Add("Size");  
  40.             dt.Columns.Add("Type");  
  41.             //Looping through Each file available in the MyUploads folder  
  42.             foreach (string str in Directory.GetFiles(Server.MapPath("~/MyUploads"))) //Directory.GetFiles Method is used to Get the files from the Folder  
  43.             {  
  44.                 FileInfo fileinfo = new FileInfo(str); //Fileinfo class is used to fetch the information about the Fetched file  
  45.                 string filename = fileinfo.Name; //Getting the Name of the File  
  46.                 string filesize = (fileinfo.Length / 1024).ToString(); //Getting the Size of the file and Converting it into KB from Bytes  
  47.                 string filetype = GetFileTypeByFileExtension(fileinfo.Extension); //Getting file Extension and Calling Custom Method  
  48.                 dt.Rows.Add(filename, filesize, filetype); //Adding Rows to the DataTable  
  49.             }  
  50.             GridView1.DataSource = dt; // Setting the Values of DataTable to be Shown in Gridview  
  51.             GridView1.DataBind(); // Binding the Data  
  52.         }  
  53.   
  54.         private string GetFileTypeByFileExtension(string fileExtension)  
  55.         {  
  56.             switch (fileExtension.ToLower()) //Checking the file Extension and Showing the Hard Coded Values on the Basis of Extension Type  
  57.             {  
  58.                 case ".doc":  
  59.                 case ".docx":  
  60.                     return "Microsoft Word Document";  
  61.                 case ".xls":  
  62.                 case ".xlsx":  
  63.                     return "Microsoft Excel Document";  
  64.                 case ".txt":  
  65.                     return "Text File";  
  66.                 case ".png":  
  67.                 case ".jpg":  
  68.                     return "Windows Image file";  
  69.                 default:  
  70.                     return "Unknown file type";  
  71.             }  
  72.         }  
  73.   
  74.     }  
  75. }  

 

Ebook Download
View all
Learn
View all