Home  »  Articles  »  ASP.Net  »

How to use Handler to fetch image from database and display that.

 Posted By : Manoranjan SahooPosted Date : 30/10/2010 06:51:56 AM Category : ASP.Net Points : 6 (Rs 1.00)

To Use Handler for displaying image any where, use the following code

Steps


1. Create one Handler.ashx file . To create one Handler file RightClick on the projectName in the solution explorer, click on the Add New Item then select Generic Handler then click on OK button
2. Place the following code in the "public class Handler : IHttpHandler {"

CODE



public void ProcessRequest (HttpContext context)
{
    SqlConnection myConnection = new SqlConnection("Put Connection string Here");
    if (myConnection.State == ConnectionState.Closed)
    {
       myConnection.Open();
    }
    string sql = "Select img from ImageDataBase where id='"+context.Request.QueryString["id"]+"'";
    SqlCommand cmd = new SqlCommand(sql, myConnection);
    cmd.Prepare();
    SqlDataReader dr = cmd.ExecuteReader();
    dr.Read();
    context.Response.BinaryWrite((byte[])dr["img"]);
    dr.Close();
    if (myConnection.State == ConnectionState.Open)
    {
        myConnection.Close();
    }
}

public bool IsReusable
{
    get
    {
        return false;
    }
}



Now use the following method to call the handler to display.
Suppose you want to display in an Image box control of ASP.Net then follow the steps.
1. Create one Image Control of ASP.Net
2. Then set the image url of that as "Image1.ImageUrl = "Handler2.ashx?id=1" ". you can set here the id number or unique number corresponding to that image.Based on this the query search for the image from the database.

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.