In this article, you will come to know about the following things:
- How to upload a file with an example image file .
- How to open an uploaded file in the browser to read.
- 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:
- Check size of the file. We can restrict the size of the file to be uploaded.
- 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
- <asp:TemplateField HeaderText="Photo">
- <ItemTemplate>
- <asp:Image ID="imgPicture" runat="server" ImageUrl='<%# Eval("FriendImage", "~/FriendPhoto/{0}") %>' Width="200px" />
- </ItemTemplate>
- </asp:TemplateField>
Code To Display Image on Another Tab: ViewImage.aspx
- protected void btnView_Click(object sender, EventArgs e)
- {
- LinkButton lnkbtn = sender as LinkButton;
- GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
- string filePath = "~//FriendPhoto//" + gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();
-
- Response.Write(String.Format("<script>window.open('{0}','_blank');</script>", "viewImage.aspx?fn=" + filePath));
- }
In GridView, we are having a button called View:
Code To Download a selected Image
- protected void btnDownload_Click(object sender, EventArgs e)
- {
- Button btn = sender as Button;
- GridViewRow gvrow = btn.NamingContainer as GridViewRow;
- string filePath = "FriendPhoto\\"+gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();
- Response.ContentType = "image/jpg";
- Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
- Response.TransmitFile(Server.MapPath(filePath));
- Response.End();
- }
Step by Step for achieving our task
- Create Project
Create a new ASP.NET Empty Web Site project named: FileUploadAndViewAndDownload,
- 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.
- <connectionStrings>
- <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"/>
- </connectionStrings>
Code FriendList.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FriendList.aspx.cs" Inherits="FriendList" EnableEventValidation="true" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <a href="NewFriend.aspx">Insert An New Friend</a>
- <asp:GridView ID="gvFriend" DataKeyNames="FriendImage" runat="server" AutoGenerateColumns="false" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
- <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
- <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
- <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
- <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
- <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
- <SortedAscendingCellStyle BackColor="#FFF1D4" />
- <SortedAscendingHeaderStyle BackColor="#B95C30" />
- <SortedDescendingCellStyle BackColor="#F1E5CE" />
- <SortedDescendingHeaderStyle BackColor="#93451F" />
- <Columns>
- <asp:BoundField DataField="FriendID" HeaderText="Friend ID"/>
- <asp:BoundField DataField="Name" HeaderText="Friend Name"/>
- <asp:BoundField DataField="Place" HeaderText="Place"/>
- <asp:BoundField DataField="Mobile" HeaderText="Mobile Number"/>
- <asp:TemplateField HeaderText="Photo">
- <ItemTemplate>
- <asp:Image ID="imgPicture" runat="server" ImageUrl='<%# Eval("FriendImage", "~/FriendPhoto/{0}") %>' Width="200px" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="View">
- <ItemTemplate>
- <asp:LinkButton ID="btnView" runat="server" Text="View" OnClick="btnView_Click" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Download">
- <ItemTemplate>
- <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" />
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
-
- </div>
- </form>
- </body>
- </html>
Code FriendList.aspx .cs
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- public partial class FriendList : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGridView();
- }
-
-
- }
-
- private void BindGridView()
- {
- string constr = ConfigurationManager.ConnectionStrings["fileuploadConnectionString"].ConnectionString;
- SqlConnection con = new SqlConnection(constr);
- SqlDataAdapter da = new SqlDataAdapter("Select * From tblFileUpload", con);
- DataSet ds = new DataSet();
- da.Fill(ds, "Friend");
- gvFriend.DataSource = ds;
- gvFriend.DataBind();
- }
-
- protected void btnView_Click(object sender, EventArgs e)
- {
- LinkButton lnkbtn = sender as LinkButton;
- GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
- string filePath = "~//FriendPhoto//" + gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();
-
- Response.Write(String.Format("<script>window.open('{0}','_blank');</script>", "viewImage.aspx?fn=" + filePath));
- }
-
- protected void btnDownload_Click(object sender, EventArgs e)
- {
- Button btn = sender as Button;
- GridViewRow gvrow = btn.NamingContainer as GridViewRow;
- string filePath = "FriendPhoto\\"+gvFriend.DataKeys[gvrow.RowIndex].Value.ToString();
- Response.ContentType = "image/jpg";
- Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
- Response.TransmitFile(Server.MapPath(filePath));
- Response.End();
- }
- }
Code NewFriend.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NewFriend.aspx.cs" Inherits="NewFriend" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <h1>Friend Detail</h1>
- <table>
- <tr>
- <td>
- Name
- </td>
- <td>
- <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- Place
- </td>
- <td>
- <asp:TextBox ID="txtPlace" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- Mobile
- </td>
- <td>
- <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- Photo/Image
- </td>
- <td>
- <asp:FileUpload ID="fuImage" runat="server" accept=".png,.PNG,.bmp,.BMP,.jpeg,.JPEG,.jpg,.JPG" ></asp:FileUpload>
- </td>
- </tr>
- <tr>
- <td>
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
- </td>
- <td>
- <asp:Button ID="btnBack" runat="server" Text="Back" OnClick="btnBack_Click" PostBackUrl="~/FriendList.aspx" />
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Code NewFriend.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.IO;
-
- public partial class NewFriend : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- }
-
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- string filename = Path.GetFileName(fuImage.PostedFile.FileName);
- string str = DateTime.Now.ToString("hhmmssffffff")+filename;
- fuImage.SaveAs(Server.MapPath("FriendPhoto/"+str));
-
- string constr = ConfigurationManager.ConnectionStrings["fileuploadConnectionString"].ConnectionString;
- SqlConnection con = new SqlConnection(constr);
- con.Open();
- SqlCommand cmd = new SqlCommand("Insert into tblFileUpload (Name,Place,Mobile, FriendImage) Values(@Name,@Place,@Mobile,@FriendImage)", con);
- cmd.Parameters.AddWithValue("@Name",txtName.Text);
- cmd.Parameters.AddWithValue("@Place",txtPlace.Text);
- cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
- cmd.Parameters.AddWithValue("@FriendImage", str);
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- con.Close();
- Response.Redirect("~/FriendList.aspx");
- }
- }
Code ViewImage.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="viewImage.aspx.cs" Inherits="viewImage" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:Image ID="Image1" runat="server" Height="408px" Width="649px" />
- </div>
- </form>
- </body>
- </html>
Code ViewImage.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- public partial class viewImage : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- string FilePath = null;
-
- FilePath = Request.QueryString["fn"];
-
- if (FilePath != null)
- {
- string path = Server.MapPath(FilePath);
- Image1.ImageUrl = FilePath;
- }
-
- }
- }
Output