Uploading And Displaying Images From DataBase Using ASP.NET C#

In this article we will learn how to upload images to, and display them from, a database.

Background

After my article Uploading Images to Database Using ASP.NET C#  I have often been asked how to upload images to a database and displaying them from the database using ASP.Net C#. So to satisfy those the requirements I decided to write this article especially focusing on beginners and those who want to learn how to upload images to a database and display those images.

Now before creating the application, let us create a table named "ImageToDB" or whatever name you wish in a database to store the uploaded image files in a database table having the following fields (shown in the following image),

Untitled.png

Then after that don't forget to set the identity specification of the id column to yes, because in this application Id is an important role for retrieving the images, if you don't know how to set it then see the following example.

When you select the id column of the above table then it shows the column properties as,

IdentitySpecification.png

Now in the image above, you see the "Is Identity" property, set it to "yes".

In the preceding table, the ImageName column name is used to store the name of an image file and the image is used to store the image file .

I hope you have created the same type of table.

Now let us start to create an application to upload and display image files step-by-step.

Now create the project as,

  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Give the project a name, such as "DisplayingImages" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - "Default.aspx" page.
  5. One File upload control, one Button, one TextBox, one label and one Image control to display images.

Then the <form> section of the Default.aspx page looks as in the following,

  1. <form id="form1" runat="server">  
  2.     <tr> Name  
  3.         <td>  
  4.             <asp:TextBox ID="TextBox1" runat="server" /> </td>  
  5.         <td>  
  6.             <td> Select Image </td>  
  7.             <td>  
  8.                 <asp:FileUpload ID="FileUpload1" runat="server" /> </td>  
  9.         </td>  
  10.     </tr>  
  11.     </table>  
  12.     <table>  
  13.         <tr>  
  14.             <td>  
  15.                 <p>  
  16.                     <asp:Label ID="Label2" runat="server" Text="label"></asp:Label>  
  17.                 </p>  
  18.             </td>  
  19.         </tr>  
  20.     </table>  
  21.     </div>  
  22. </form>  

Now we need to add a Handler file to our project to display images from the database because we are saving images in binary format to get the binary formatted data we are using the Handler class. To know more about the handler class please refer to the MSDN forum.

Adding Handler Class

1. Right-click on your project add a new Handler1.ashx file as,

handler.png

In the preceding image, we can see the .ashx extension file, now keep the name as it is or change it as you wish, I have kept it as it is because the next time you can easily remember it and click on the add button, now after that your Solution Explorer will look as in the following,

Solutionexpl.png

Now switch to design mode to code behind and create the following method to upload the image files as,

  1. private void Imageupload()  
  2. {  
  3.     if (FileUpload1.HasFile)  
  4.     {  
  5.         int imagefilelenth = FileUpload1.PostedFile.ContentLength;  
  6.         byte[] imgarray = new byte[imagefilelenth];  
  7.         HttpPostedFile image = FileUpload1.PostedFile;  
  8.         image.InputStream.Read(imgarray, 0, imagefilelenth);  
  9.         connection();  
  10.         query = "Insert into ImageToDB (ImageName, Image) values (@Name, @Image)";  
  11.         SqlCommand com = new SqlCommand(query, con);  
  12.         com.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = TextBox1.Text;  
  13.         com.Parameters.AddWithValue("@Image", SqlDbType.Image) Value = imgarray;  
  14.         com.ExecuteNonQuery();  
  15.         Label1.Visible = true;  
  16.         Label1.Text = "Image Is Uploaded successfully";  
  17.         imagebindGrid();  
  18.     }  
  19. }  
Now double-click on the "Imageupload" button and call the preceding method on it as,

  1. protected void upload(object sender, EventArgs e)  
  2. {  
  3.     Imageupload();  
  4. }  

Now, create the method to bind to the GridView as,

  1. public void imagebindGrid()  
  2. {  
  3.     connection();  
  4.     query = "Select id, ImageName, Image from ImageToDB";  
  5.     SqlCommand com = new SqlCommand(query, con);  
  6.     SqlDataReader dr = com.ExecuteReader();  
  7.     Gridview1.DataSource = dr;  
  8.     Gridview1.DataBind();  
  9. }  

And call preceding "Imagebindgirdmethod"() on page load as,

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Label1.Visible = false;  
  4.     if (!IsPostBack)  
  5.         imagebindGrid();  
  6. }  
Now, open the "Handler1.ashx.cs" and write the following code,

  1. public class Handler1 : IHttpHandler  
  2. {  
  3.     //creating the object of Default.aspx class page to  
  4.     //call connection and use strings variable  
  5.     Default cls = new Default();  
  6.     public void ProcessRequest(HttpContext context)  
  7.     {  
  8.         //storing the querystring value that comes from Default aspx page  
  9.         string displayimgid = context.Request.QueryString["id_Image"].ToString();  
  10.         cls.connection();  
  11.         //retrieving the images on the basis of id of uploaded  
  12.         // images, by using the query sting values which comes from Defaut.aspx page  
  13.         cls.query = "select Image from ImageToDB where id=" + displayimgid;  
  14.         SqlCommand com = new SqlCommand(cls.query, cls.con);  
  15.         SqlDataReader dr = com.ExecuteReade();  
  16.         dr.Read();  
  17.         context.Response.BinaryWrite((Byte[])dr[0]);  
  18.         context.Response.End();  
  19.     }  
  20. }  

In the preceding Handler1.ashx.cs file, first I have created the object of the default.aspx.cs class to use the connection method and variable to avoid the repetition of code because in the handler.ashx.cs file we also need the same connection method and string variables that are in the default.aspx.cs class.

Now, the most important thing is to specify the image URL property of the image control that display the images from the database, so let us see how to do it.

ImageUrl='<%# "Handler1.ashx?id_Image="+ Eval("id") %>' 

 

Now run, the application that will look like as in the following,

run.png

Now upload the images that will display the output as follows,

ouputimage.png

In preceding output, you can clearly see that my uploaded image is displayed in the GridView with file name and image.

Note

  • For detailed code please download the zip file attached above.
  • Don't forget to update the "Web.config" file for your server location.

Summary

Now we have learned how to upload images to a database and display those images in GridView. I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.