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.
- <!DOCTYPE html>
- <html>
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <%--ASP.NET control to upload a file--%>
- <asp:FileUpload ID="FileUpload1" runat="server" />
- <%--Button to Upload the file--%>
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload File" />
- <br />
- <br />
- <br />
- <%--Gridview to Display the Available data with file Details--%>
- <%--Generate the OnRowCommand Event Handler of the Gridview Control--%>
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" Width="513px">
- <AlternatingRowStyle BackColor="White" />
- <Columns>
- <%--Item Template is used to Add a custom link button whose Eval Binding is "File"--%>
- <asp:TemplateField HeaderText="File Name">
- <ItemTemplate>
- <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("File") %>' Text='<%# Eval("File") %>'></asp:LinkButton>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:BoundField DataField="Size" HeaderText="Size (KB)" />
- <asp:BoundField DataField="Type" HeaderText="File Type with Extension" />
- </Columns>
- <EditRowStyle BackColor="#2461BF" />
- <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
- <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
- <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
- <RowStyle BackColor="#EFF3FB" />
- <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
- <SortedAscendingCellStyle BackColor="#F5F7FB" />
- <SortedAscendingHeaderStyle BackColor="#6D95E1" />
- <SortedDescendingCellStyle BackColor="#E9EBEF" />
- <SortedDescendingHeaderStyle BackColor="#4870BE" />
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>
- using System;
- using System.Data;
- using System.IO;
- using System.Web.UI.WebControls;
- namespace FileUploadAndDownloadDemo
- {
- public partial class Index : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack) //Used to Check whether the Page is loaded first time or not
- {
- ListOfData(); //Custom Method Called
- }
- }
- protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) //Is fired when File is Downloaded
- {
- Response.Clear();
- Response.ContentType = "application/octet-stream";
- Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument); //Used to append the filename at the time of Downloading
- Response.TransmitFile(Server.MapPath("~/MyUploads/") + e.CommandArgument); //Used to Fetch the file from the Physical folder of Server
- Response.End();
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- if (FileUpload1.HasFile) //If the used Uploaded a file
- {
- string FileName = FileUpload1.FileName; //Name of the file is stored in local Variable
- FileUpload1.PostedFile.SaveAs(Server.MapPath("~/MyUploads/") + FileName); //File is saved in the Physical folder
- }
- ListOfData(); //Custom method is Called
- }
- //Custom Methods used in the Above Code
- private void ListOfData()
- {
- DataTable dt = new DataTable(); //Datatable is Created to Add Dynamic Columns
- //Columns Added with the Same name as that of Eval Expression and the DataField Value of the Gridview
- dt.Columns.Add("File");
- dt.Columns.Add("Size");
- dt.Columns.Add("Type");
- //Looping through Each file available in the MyUploads folder
- foreach (string str in Directory.GetFiles(Server.MapPath("~/MyUploads"))) //Directory.GetFiles Method is used to Get the files from the Folder
- {
- FileInfo fileinfo = new FileInfo(str); //Fileinfo class is used to fetch the information about the Fetched file
- string filename = fileinfo.Name; //Getting the Name of the File
- string filesize = (fileinfo.Length / 1024).ToString(); //Getting the Size of the file and Converting it into KB from Bytes
- string filetype = GetFileTypeByFileExtension(fileinfo.Extension); //Getting file Extension and Calling Custom Method
- dt.Rows.Add(filename, filesize, filetype); //Adding Rows to the DataTable
- }
- GridView1.DataSource = dt; // Setting the Values of DataTable to be Shown in Gridview
- GridView1.DataBind(); // Binding the Data
- }
- private string GetFileTypeByFileExtension(string fileExtension)
- {
- switch (fileExtension.ToLower()) //Checking the file Extension and Showing the Hard Coded Values on the Basis of Extension Type
- {
- case ".doc":
- case ".docx":
- return "Microsoft Word Document";
- case ".xls":
- case ".xlsx":
- return "Microsoft Excel Document";
- case ".txt":
- return "Text File";
- case ".png":
- case ".jpg":
- return "Windows Image file";
- default:
- return "Unknown file type";
- }
- }
- }
- }

Join the conversation! Your thoughts help the community grow.