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. <html>
  3. <head runat="server">
  4. <title></title>
  5. </head>
  6. <body>
  7. <form id="form1" runat="server">
  8. <div>
  9. <%--ASP.NET control to upload a file--%>
  10. <asp:FileUpload ID="FileUpload1" runat="server" />
  11. <%--Button to Upload the file--%>
  12. <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload File" />
  13. <br />
  14. <br />
  15. <br />
  16. <%--Gridview to Display the Available data with file Details--%>
  17. <%--Generate the OnRowCommand Event Handler of the Gridview Control--%>
  18. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" Width="513px">
  19. <AlternatingRowStyle BackColor="White" />
  20. <Columns>
  21. <%--Item Template is used to Add a custom link button whose Eval Binding is "File"--%>
  22. <asp:TemplateField HeaderText="File Name">
  23. <ItemTemplate>
  24. <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("File") %>' Text='<%# Eval("File") %>'></asp:LinkButton>
  25. </ItemTemplate>
  26. </asp:TemplateField>
  27. <asp:BoundField DataField="Size" HeaderText="Size (KB)" />
  28. <asp:BoundField DataField="Type" HeaderText="File Type with Extension" />
  29. </Columns>
  30. <EditRowStyle BackColor="#2461BF" />
  31. <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  32. <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  33. <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  34. <RowStyle BackColor="#EFF3FB" />
  35. <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  36. <SortedAscendingCellStyle BackColor="#F5F7FB" />
  37. <SortedAscendingHeaderStyle BackColor="#6D95E1" />
  38. <SortedDescendingCellStyle BackColor="#E9EBEF" />
  39. <SortedDescendingHeaderStyle BackColor="#4870BE" />
  40. </asp:GridView>
  41. </div>
  42. </form>
  43. </body>
  44. </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. private string GetFileTypeByFileExtension(string fileExtension)
  54. {
  55. switch (fileExtension.ToLower()) //Checking the file Extension and Showing the Hard Coded Values on the Basis of Extension Type
  56. {
  57. case ".doc":
  58. case ".docx":
  59. return "Microsoft Word Document";
  60. case ".xls":
  61. case ".xlsx":
  62. return "Microsoft Excel Document";
  63. case ".txt":
  64. return "Text File";
  65. case ".png":
  66. case ".jpg":
  67. return "Windows Image file";
  68. default:
  69. return "Unknown file type";
  70. }
  71. }
  72. }
  73. }