Image Store and Retrieve From Database Using Generic Handler in ASP.Net

In this example we will store employee information with an employee image preview and display the inserted employee information with PhotoID in GridView.

Now to start this example step-by-step.

Step 1

This is the database side.

First create an EmployeeImage table in the SQL database as in the following.

  1. create Table EmployeeImage  
  2. (  
  3. ImageId int identity(1,1), --- make auto increment id  
  4. ImgName nvarchar(50),  
  5. Photo image,  
  6. Contact nvarchar(15),  
  7. Designation varchar(50)  
  8. )  
Step 2

Go to Visual Studio.

Step 3

This is the Page Design.

Here open your project and add a new .aspx page as in the following.

Now right-click on your project name and add a new item to the project.

Add New Item
Figure 1: Add New Item

Click on new item and add a new webform and provide a suitable name as follows:
Add Design Page
Figure 2: Add Design Page

First write the image upload and display the preview code using the jQuery function as in the following:
  1. <script type="text/javascript">  
  2.    function previewFile() {  
  3.        var ImagePreview = document.querySelector('#<%=ImgUpload.ClientID %>');  
  4.        var ImageFile = document.querySelector('#<%=FileUpload.ClientID %>').files[0];  
  5.        var reader = new FileReader();  
  6.   
  7.        reader.onloadend = function () {  
  8.            ImagePreview.src = reader.result;  
  9.        }  
  10.   
  11.        if (ImageFile) {  
  12.            reader.readAsDataURL(ImageFile);  
  13.        } else {  
  14.            ImagePreview.src = "";  
  15.        }  
  16.    }  
  17. </script>  
Second write the design code for the employee information insert screen as follows:
  1. <div>  
  2. <fieldset style="width: 490px"><legend>Employee Information With PhotoID</legend>  
  3.     <asp:Table runat="server" Width="442px" >  
  4.          
  5.         <asp:TableRow>  
  6.             <asp:TableCell></asp:TableCell><asp:TableCell><asp:Image ID="ImgUpload" ToolTip="Upload Employee Photo Here" runat="server" Height="200px"  Width="200px" /></asp:TableCell>  
  7.         </asp:TableRow>  
  8.   
  9.              <asp:TableRow>  
  10.                 <asp:TableCell> Upload Image:</asp:TableCell><asp:TableCell> <input ID="FileUpload" type="file" name="file" onchange="previewFile()"  runat="server" /></asp:TableCell>  
  11.             </asp:TableRow>  
  12.   
  13.          <asp:TableRow>  
  14.             <asp:TableCell>Employee Name:</asp:TableCell><asp:TableCell><asp:TextBox ID="txtName" runat="server"></asp:TextBox> </asp:TableCell>  
  15.         </asp:TableRow>  
  16.   
  17.         <asp:TableRow>  
  18.             <asp:TableCell>Contact</asp:TableCell><asp:TableCell><asp:TextBox ID="txtContact" runat="server" ></asp:TextBox></asp:TableCell>  
  19.         </asp:TableRow>  
  20.   
  21.         <asp:TableRow>  
  22.             <asp:TableCell>Designation</asp:TableCell><asp:TableCell><asp:TextBox ID="txtDesignation" runat="server" ></asp:TextBox></asp:TableCell>  
  23.         </asp:TableRow>  
  24.           
  25.         <asp:TableRow>  
  26.             <asp:TableCell></asp:TableCell><asp:TableCell><asp:Button ID="btnDataInsert" runat="server" Text="SUBMIT" onclick="btnDataInsert_Click" /></asp:TableCell>  
  27.         </asp:TableRow>  
  28.   
  29.     </asp:Table>  
  30.       
  31. </fieldset>  
  32. </div>  
Add a GridView to display the employee information with the employee's PhotoID.
  1. <div>  
  2.     <asp:GridView ID="GridEmpImg" runat="server" AutoGenerateColumns="False">  
  3.         <Columns>  
  4.         <asp:TemplateField HeaderText="Image">  
  5.         <ItemTemplate>  
  6.         <asp:Image ID="Image1" runat="server" ImageUrl='<%# "DisplayImage.ashx?ImageId="+ Eval("ImageId") %>' Height="150px" Width="150px"/>  
  7.         </ItemTemplate>  
  8.         </asp:TemplateField>  
  9.         <asp:BoundField HeaderText = "Employee Name" DataField="imgname" />  
  10.         <asp:BoundField HeaderText = "Contact" DataField="Contact" />  
  11.         <asp:BoundField HeaderText = "Designation" DataField="Designation" />  
  12.         </Columns>  
  13.     </asp:GridView>  
  14. </div>  
Finally our design for the preceding code will be as follows:

UI Design
Figure 3: UI Design

Step 4

Add a Connection String in the web.config file as in the following:
  1. <connectionStrings>  
  2.     <add name="connstr" connectionString="Data Source=RAKESH-PC;Initial Catalog=SqlServerTech;User ID=sa;Password=jm" providerName="System.Data.SqlClient"/>  
  3.     <add name="Pratical_testConnectionString" connectionString="Data Source=RAKESH-PC;Initial Catalog=Pratical_test;User ID=sa" providerName="System.Data.SqlClient"/>  
  4.   </connectionStrings>  
Step 5

This is the Page code.

In this section we will write the image upload code, insert code and select employee information with PhotoId code using a generic file method HttpHandler as follows:
  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.Configuration;  
  8. using System.Data.SqlClient;  
  9. using System.Data;  
  10. using System.IO;  
  11.   
  12.   
  13. namespace Test_WebApplication.ImageCode  
  14. {  
  15.     public partial class ImageDemo : System.Web.UI.Page  
  16.     {  
  17.         string constring = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;  
  18.         protected void Page_Load(object sender, EventArgs e)  
  19.         {  
  20.             EmpImageInfo();  
  21.         }  
  22.   
  23.        protected void Upload(object sender, EventArgs e)  
  24.         {  
  25.            string fileName = FileUpload.PostedFile.FileName;  
  26.         }  
  27.   
  28.        protected void btnDataInsert_Click(object sender, EventArgs e)  
  29.        {  
  30.            int length = FileUpload.PostedFile.ContentLength;  
  31.   
  32.            byte[] imgbyte = new byte[length];  
  33.   
  34.            HttpPostedFile image = FileUpload.PostedFile;  
  35.   
  36.            image.InputStream.Read(imgbyte, 0, length);  
  37.            string ImgName = txtName.Text;  
  38.            string Contact = txtContact.Text;  
  39.            string Designation = txtDesignation.Text;  
  40.   
  41.            SqlConnection conn = new SqlConnection(constring);  
  42.            conn.Open();  
  43.            SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeImage (ImgName,photo,Contact,Designation) VALUES (@ImgName,@photo,@Contact,@Designation)", conn);  
  44.            cmd.Parameters.Add("@ImgName", SqlDbType.VarChar, 50).Value = ImgName;  
  45.            cmd.Parameters.Add("@photo", SqlDbType.Image).Value = imgbyte;  
  46.            cmd.Parameters.Add("@Contact", SqlDbType.NVarChar, 15).Value = Contact;  
  47.            cmd.Parameters.Add("@Designation", SqlDbType.VarChar, 50).Value = Designation;  
  48.            int count = cmd.ExecuteNonQuery();  
  49.            conn.Close();  
  50.   
  51.            if (count == 1)  
  52.            {  
  53.                EmpImageInfo();  
  54.                ScriptManager.RegisterStartupScript(thisthis.GetType(), "alertmessage""javascript:alert('" + ImgName + " PhotoID Information Inserted successfully')"true);  
  55.            }  
  56.            txtName.Text = string.Empty;  
  57.            txtContact.Text = string.Empty;  
  58.            txtDesignation.Text = string.Empty;  
  59.        }  
  60.   
  61.        private void EmpImageInfo()  
  62.         {  
  63.             SqlConnection conn = new SqlConnection(constring);  
  64.             SqlCommand cmd = new SqlCommand("SELECT ImageId, ImgName,Photo,Contact,Designation from EmployeeImage", conn);  
  65.             SqlDataAdapter da = new SqlDataAdapter(cmd);  
  66.             DataTable dt = new DataTable();  
  67.             da.Fill(dt);  
  68.             GridEmpImg.DataSource = dt;  
  69.             GridEmpImg.DataBind();  
  70.        }  
  71.          
  72.     }  
  73. }  
Step 6

Add a .ashx.cs file to the project.

Now add one more important file, a generic handler, to the project for the image display in the GridView as follows:

Add Generic File
Figure 4: Add Generic File

Now write the generic handler code to display the image from the database as in the following:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Configuration;  
  6. using System.Data.SqlClient;  
  7. using System.IO;  
  8. using System.Data;  
  9.   
  10. namespace Test_WebApplication.ImageCode  
  11. {  
  12.     public class DisplayImage : IHttpHandler  
  13.     {  
  14.         string constring = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;  
  15.         public void ProcessRequest(HttpContext context)  
  16.         {  
  17.             string ImageId = context.Request.QueryString["ImageId"];  
  18.             SqlConnection conn = new SqlConnection(constring);  
  19.             conn.Open();  
  20.             SqlCommand cmd = new SqlCommand("select Photo from EmployeeImage where ImageId=" + ImageId, conn);  
  21.             SqlDataReader dr = cmd.ExecuteReader();  
  22.             dr.Read();  
  23.             context.Response.BinaryWrite((Byte[])dr[0]);  
  24.             conn.Close();  
  25.             context.Response.End();  
  26.         }  
  27.   
  28.         public bool IsReusable  
  29.         {  
  30.             get  
  31.             {  
  32.                 return false;  
  33.             }  
  34.         }  
  35.     }  
  36. }  
Step 7

Run the code in a browser by pressing F5.

UI on Browser
Figure 5: UI on Browser

Choose an image file from disk.

Choose file from disk
Figure 6: Choose file from disk

Showing the image preview as follows:

Image Preview
Figure 7: Image Preview

Now click the submit button and you will get a record insert message in a dialog box as in the following:

Message Display
Figure 8: Message Display

The inserted employee record is shown in the GridView control.

Inserted Record Display
Figure 9: Inserted Record Display

Also check in the database table as in the following:

Data Store Database
Figure 10: 

In the preceding figure you can see that the image was stored in binary data format.