File Upload, View And Download in ASP.NET

In this article, you will come to know about the following things:

  1. How to upload a file with an example image file .
  2. How to open an uploaded file in the browser to read.
  3. How to download an uploaded file.

In many scenarios, we have to develop, upload, and open the uploaded file in the Browser and download an uploaded file.

Upload a File : (NewFriend.aspx)

In this page, we will accept and insert a new friend with the image.

Friend List: (FriendList.aspx)

This page will display the friends with the images. There are two buttons, View and Download.

  • View Button : Click this button and it will redirect you on ViewImage.aspx
  • Download Button : Click this button and the image will download.

File Upload

We can upload and receive the file from the user with the help of FileUpload control. We can receive/ allow the upload with the following points:

  1. Check size of the file. We can restrict the size of the file to be uploaded.
  2. Extension of the file. We can restrict the extension of file to be uploaded.

While we are accepting the file from the user through the file upload, always feed extra information in the file name like: DateTime , UserID or Friend ID etc..

When Web master or site administrator will view the image folder, here, we will only upload the image and View on new tab of the Browser and download the same.

Code To Display Image in Friend List page : FriendList.aspx

  1. <asp:TemplateField HeaderText="Photo">  
  2.     <ItemTemplate>  
  3.        <asp:Image ID="imgPicture" runat="server" ImageUrl='<%# Eval("FriendImage", "~/FriendPhoto/{0}") %>' Width="200px" />  
  4.      </ItemTemplate>  
  5. </asp:TemplateField>  
Code To Display Image on Another Tab: ViewImage.aspx
  1. protected void btnView_Click(object sender, EventArgs e)  
  2. {  
  3.     LinkButton lnkbtn = sender as LinkButton;  
  4.     GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;  
  5.     string filePath = "~//FriendPhoto//" + gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();  
  6.   
  7.     Response.Write(String.Format("<script>window.open('{0}','_blank');</script>""viewImage.aspx?fn=" + filePath));  
  8. }  
In GridView, we are having a button called View: 

Code To Download a selected Image
  1. protected void btnDownload_Click(object sender, EventArgs e)  
  2. {  
  3.     Button btn = sender as Button;  
  4.     GridViewRow gvrow = btn.NamingContainer as GridViewRow;  
  5.     string filePath = "FriendPhoto\\"+gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();  
  6.     Response.ContentType = "image/jpg";  
  7.     Response.AddHeader("Content-Disposition""attachment;filename=\"" + filePath + "\"");  
  8.     Response.TransmitFile(Server.MapPath(filePath));  
  9.     Response.End();  
  10. }  
Step by Step for achieving our task 
  • Create Project
    Create a new ASP.NET Empty Web Site project named: FileUploadAndViewAndDownload,

    Create Project

  • Add three Web Forms named as following:

    Web Form File Name Descripton
    FriendList.aspx To display all our friends in the grid view.
    NewFriend.aspx To insert a new friend in database table called tblFileUpload.
    ViewImage.aspx To display a new friend in the new Browser tab.

  • Add new Folder
    Create a new folder called FRIENDPHOTO.

  • Web.Config 
    Update your webconfig file with your SQL Server settings.
    1. <connectionStrings>  
    2.  <add name="fileuploadConnectionString" connectionString="Data Source=192.168.1.50\sa;Initial Catalog=mbktest;Persist Security Info=True;User ID=sa;Password=clserver" providerName="System.Data.SqlClient"/>  
    3.   </connectionStrings>  

Code FriendList.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FriendList.aspx.cs" Inherits="FriendList" EnableEventValidation="true" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <a href="NewFriend.aspx">Insert An New Friend</a>  
  13.         <asp:GridView ID="gvFriend" DataKeyNames="FriendImage" runat="server" AutoGenerateColumns="false" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">  
  14.             <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
  15.             <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />  
  16.             <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
  17.             <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
  18.             <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
  19.             <SortedAscendingCellStyle BackColor="#FFF1D4" />  
  20.             <SortedAscendingHeaderStyle BackColor="#B95C30" />  
  21.             <SortedDescendingCellStyle BackColor="#F1E5CE" />  
  22.             <SortedDescendingHeaderStyle BackColor="#93451F" />  
  23.             <Columns>  
  24.                 <asp:BoundField  DataField="FriendID" HeaderText="Friend ID"/>  
  25.                 <asp:BoundField  DataField="Name" HeaderText="Friend Name"/>  
  26.                 <asp:BoundField  DataField="Place" HeaderText="Place"/>  
  27.                 <asp:BoundField  DataField="Mobile" HeaderText="Mobile Number"/>  
  28.                 <asp:TemplateField HeaderText="Photo">  
  29.                         <ItemTemplate>  
  30.                             <asp:Image ID="imgPicture" runat="server" ImageUrl='<%# Eval("FriendImage", "~/FriendPhoto/{0}") %>' Width="200px" />  
  31.                          </ItemTemplate>  
  32.                 </asp:TemplateField>  
  33.                 <asp:TemplateField HeaderText="View">  
  34.                     <ItemTemplate>  
  35.                         <asp:LinkButton ID="btnView" runat="server" Text="View" OnClick="btnView_Click" />  
  36.                     </ItemTemplate>  
  37.                 </asp:TemplateField>  
  38.                 <asp:TemplateField HeaderText="Download">  
  39.                     <ItemTemplate>  
  40.                         <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" />  
  41.                     </ItemTemplate>  
  42.                 </asp:TemplateField>  
  43.             </Columns>  
  44.         </asp:GridView>  
  45.       
  46.     </div>  
  47.     </form>  
  48. </body>  
  49. </html>  
Code FriendList.aspx .cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10.   
  11. public partial class FriendList : System.Web.UI.Page  
  12. {  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         if (!IsPostBack)  
  16.         {  
  17.             BindGridView();  
  18.         }          
  19.     }  
  20.   
  21.     private void BindGridView()  
  22.     {  
  23.         string constr = ConfigurationManager.ConnectionStrings["fileuploadConnectionString"].ConnectionString;  
  24.         SqlConnection con = new SqlConnection(constr);  
  25.         SqlDataAdapter da = new SqlDataAdapter("Select * From tblFileUpload", con);  
  26.         DataSet ds = new DataSet();  
  27.         da.Fill(ds, "Friend");  
  28.         gvFriend.DataSource = ds;  
  29.         gvFriend.DataBind();  
  30.     }  
  31.     
  32.     protected void btnView_Click(object sender, EventArgs e)  
  33.     {  
  34.         LinkButton lnkbtn = sender as LinkButton;  
  35.         GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;  
  36.         string filePath = "~//FriendPhoto//" + gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();  
  37.   
  38.         Response.Write(String.Format("<script>window.open('{0}','_blank');</script>""viewImage.aspx?fn=" + filePath));  
  39.     }  
  40.   
  41.     protected void btnDownload_Click(object sender, EventArgs e)  
  42.     {  
  43.         Button btn = sender as Button;  
  44.         GridViewRow gvrow = btn.NamingContainer as GridViewRow;  
  45.         string filePath = "FriendPhoto\\"+gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();  
  46.         Response.ContentType = "image/jpg";  
  47.         Response.AddHeader("Content-Disposition""attachment;filename=\"" + filePath + "\"");  
  48.         Response.TransmitFile(Server.MapPath(filePath));  
  49.         Response.End();  
  50.     }  
  51. }  
Code NewFriend.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NewFriend.aspx.cs" Inherits="NewFriend" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <h1>Friend Detail</h1>  
  13.         <table>  
  14.             <tr>  
  15.                 <td>  
  16.                     Name  
  17.                 </td>  
  18.                 <td>  
  19.                     <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  
  20.                 </td>  
  21.             </tr>  
  22.             <tr>  
  23.                 <td>  
  24.                     Place  
  25.                 </td>  
  26.                 <td>  
  27.                     <asp:TextBox ID="txtPlace" runat="server"></asp:TextBox>  
  28.                 </td>  
  29.             </tr>  
  30.             <tr>  
  31.                 <td>  
  32.                     Mobile  
  33.                 </td>  
  34.                 <td>  
  35.                     <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>  
  36.                 </td>  
  37.             </tr>  
  38.             <tr>  
  39.                 <td>  
  40.                     Photo/Image  
  41.                 </td>  
  42.                 <td>  
  43.                     <asp:FileUpload ID="fuImage" runat="server" accept=".png,.PNG,.bmp,.BMP,.jpeg,.JPEG,.jpg,.JPG" ></asp:FileUpload>     
  44.                 </td>  
  45.             </tr>  
  46.             <tr>  
  47.                 <td>  
  48.                     <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />  
  49.                 </td>  
  50.                 <td>  
  51.                     <asp:Button ID="btnBack" runat="server" Text="Back" OnClick="btnBack_Click" PostBackUrl="~/FriendList.aspx" />  
  52.                 </td>  
  53.             </tr>  
  54.         </table>  
  55.     </div>  
  56.     </form>  
  57. </body>  
  58. </html>  
Code NewFriend.aspx.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.Configuration;  
  10. using System.IO;  
  11.   
  12. public partial class NewFriend : System.Web.UI.Page  
  13. {  
  14.     protected void Page_Load(object sender, EventArgs e)  
  15.     {  
  16.   
  17.     }  
  18.   
  19.     protected void btnSubmit_Click(object sender, EventArgs e)  
  20.     {  
  21.         string filename = Path.GetFileName(fuImage.PostedFile.FileName);  
  22.         string str = DateTime.Now.ToString("hhmmssffffff")+filename;  
  23.         fuImage.SaveAs(Server.MapPath("FriendPhoto/"+str));  
  24.   
  25.         string constr = ConfigurationManager.ConnectionStrings["fileuploadConnectionString"].ConnectionString;  
  26.         SqlConnection con = new SqlConnection(constr);  
  27.         con.Open();  
  28.         SqlCommand cmd = new SqlCommand("Insert into tblFileUpload (Name,Place,Mobile, FriendImage) Values(@Name,@Place,@Mobile,@FriendImage)", con);  
  29.         cmd.Parameters.AddWithValue("@Name",txtName.Text);  
  30.         cmd.Parameters.AddWithValue("@Place",txtPlace.Text);  
  31.         cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);  
  32.         cmd.Parameters.AddWithValue("@FriendImage", str);  
  33.         cmd.ExecuteNonQuery();  
  34.         cmd.Dispose();  
  35.         con.Close();  
  36.         Response.Redirect("~/FriendList.aspx");  
  37.     }  
  38. }  
Code ViewImage.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="viewImage.aspx.cs" Inherits="viewImage" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:Image ID="Image1" runat="server" Height="408px" Width="649px" />  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html>  
Code ViewImage.aspx.cs 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8.   
  9. public partial class viewImage : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.         string FilePath = null;  
  14.   
  15.         FilePath = Request.QueryString["fn"];  
  16.   
  17.         if (FilePath != null)  
  18.         {  
  19.             string path = Server.MapPath(FilePath);  
  20.             Image1.ImageUrl = FilePath;  
  21.         }  
  22.   
  23.     }  
  24. }  
Output

Output