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.

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. Response.Write(String.Format("<script>window.open('{0}','_blank');</script>", "viewImage.aspx?fn=" + filePath));
  7. }
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

Code FriendList.aspx

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

Output