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

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.


Thank You.

Regards,
Manoranjan Sahoo
http://msahoo.wordpress.com


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: