Skip to main content

Display Images from SQL Server in ASP.NET Page with Generic Handler

In order to display an image stored in SQL Server on the Web Form, we need the concept of Generic Handler in ASP.NET. A Generic Handler is just any other web form that is added in the current form. A generic handler is responsible for fulfilling requests from a browser. A handler is a class that implements IHttpHandler interface. Normally the generic handler is having an extension of “Handler.ashx”.

In my previous post, I discussed about the storing of an image in SQL Server which the user selects on the web page (.aspx) page. I will be continuing from the same process. The following interface is used:


In the above screen shot, a textbox is there in which the Image id will be entered by the user which the user wants to display. Also the button will be used to show the same. And lastly an image control that will display the image fetched from the database.


On the Show Image button the following coding is to be done. The hander is invoked with the help of following code:

Protected void ShowImage_Click(object sender, EventArgs e)
{
       Image1.ImageUrl = “Hander.ashx?id=”+TextBox1.Text;
}
Next Step is to add a generic handler from WebSite Menu and select Add new Item:



using System;
using System.Web;
using System.Data.SqlClient;

public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
       context.Response.ContentType = "text/plain";
       context.Response.Write("Hello World");
       String vImageID = context.Request.QueryString["id"];
       SqlConnection vConn = new SqlConnection();
       vConn.Open();
       String vQuery = "Select * From ImageTable where id = @id";
       SqlCommand vComm=new SqlCommand (vQuery,vConn);
       vComm.Parameters.AddWithValue("@id",vImageID);
       SqlDataReader myReader= vComm.ExecuteReader();
      while(myReader.Read())
      {
          context.Response.ContentType="image/jpg";
          context.Response.BinaryWrite((byte[])myReader["Photo"]);
      }
      myReader.Close();
     vConn.Close();
   }
   public bool IsReusable {
  get {
        return false;
     }
 }
}

In the above coding, we are trying to get the ID of the image which the user has entered in the previous page. And then we are doing the following stuff:

1. Open the database connection.

2. Fire query which gets the image of the selected user id which the user has passed from the previous page.

3. Reading the image in the form of DataReader.

4. And ultimately writing the DataReader with the help of context.Response.BinaryWrite. When we use this we need to typecast in the format of byte[] array because the image is also stored in the format of bytes.

I hope this article will help you in displaying images on web form (.aspx) page that are fetched out from a database.

Have nice time....

Comments

Gautam said…
THIS IS ONE LINE CODE TO, HOW TO RETRIVE (IMAGE)DATA FROM SQL

byte[] blob = (byte[])rd["PicImage"];
MemoryStream ms = new MemoryStream(blob);
ms.Write(blob, 0, (int)blob.Length);
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(ms.ToArray());

Popular posts from this blog

SQLServer Error: 15404, Could not obtain information about Windows NT group/user Error code 0x5. [SQLSTATE 42000] (ConnIsLoginSysAdmin)

If we encounter this error "SQLServer Error: 15404, Could not obtain information about Windows NT group/user Error code 0x5. [SQLSTATE 42000] (ConnIsLoginSysAdmin)" in SQL Server in which the job fails because of the user account related problem, then we need to take the following steps to make it work: a. Go to SQL Server Agent. b. Then select the job which is giving error and not running successfully. c. Then choose properties and in the General Tab, change the owner to "SA" or any account that has the administrative privileges. The problem will be resolved.

Connecting Nodejs to SQL Server with Knex ORM - Part 1

Normally we connect Nodejs to the databases like SQLite, MongoDB, Postgres etc . In this multiple part post, I am going to show you, how we can connect Nodejs with Microsoft's SQL Server using Knex and run CRUD operations. 1. Installation of required packages In order to connect Nodejs to SQL Server with Knex, we will need following node packages installation: i. npm install knex ii. npm install mssql Once the packages are installed, we can write the following code to connect: //Code to KNEX connection settings. var knex = require('knex')({ client: 'mssql', connection: { user: 'sa', password: 'pwd', server: 'localhost', database: 'Test' } }); //Code to query the Table DEPT knex.select("*").from("dept") .then(function (depts){ depts.forEach((dept)=>{ //use of Arrow Function console.log({...dept}); }); }).catch(function(err) { ...

How to use QueryExtenderControl in ASP.NET with LINQ

Queryextender control is a control that helps in doing actions like filtration, searching, sorting etc. on the LINQ Data source with few steps. In fact we don’t have to write any code with this. Screenshot given below is just an example that can easily be achieved through this control. In the above screenshot, we can see that there is a GridView Control that has been binded to a LINQData Source Control. And we have a DropDownlistBox that is also binded to another LINQData Source Control and displaying only grouped jobs. The GridView display all the employees who are matching the Job Parameter. This is done through QueryExtender Control. Also we can search for any name in the employee name's through Query Extender control. The code in the HTML goes like: < form id ="form1" runat ="server">     < div >         Select Job: < asp : DropDownList ID ="Job" runat ="server" DataSourceID ="LinqDataSource2...