Introduction
Retrieving images dynamically from database based on filename can be quite simple. What we normally do is store all the images on certain folder , get the file name from the database, and then set the image server control path based on the filename and path that we get from database.
In this tutorial, I will show you how to simplify the code of displaying images by using the HttpHandler. By using HTTPHandler, you only need one single line of html code to dynamically find and display your images from database regardless of you are storing the image only or you are storing the image data.
What is HTTPHandler
HttpHandlers are the earliest possible point where we have access to the requests made to the web server (IIS). When a request is made to the web server for an ASP.NET resource (.aspx, .asmx, etc.), the worker process of the ASP.NET creates the right HttpHandler for the request which responds to the request. The default handlers for each request type that ASP.NET handles are set in the machine.config file. For example, all the requests made to ASP.NET (.aspx) pages are handled by System.Web.UI.PageHandlerFactory. So whenever an ASP.NET is requested at the web server, the PageHandlerFactory will fulfill the request.
Why Http Handlers
Creating an HttpHandler
Now, lets start coding HttpHandler.
Create new ashx file from VisualStudio
<%@ WebHandler Language="C#" Class="getImage" %>
using System;
using System.Web;
using dsImagesTableAdapters;
public class DisplayImage: IHttpHandler {
public void ProcessRequest (HttpContext context) {
int iImageId;
if (context.Request.QueryString["id"] != null)
{
iImageId = Convert.ToInt32(context.Request.QueryString["id"]);
}
else {
throw new ArgumentException("No parameter specified");
}
DataSet dsImages = GetDataSetImagesfromDatabase();
DataTable dtImgTable = dsImages.Tables[0];
if (dtImgTable .Rows.Count > 0)
{
if (dtImgTable [0]["Image"] != DBNull.Value)
{
context.Response.ContentType =
dtImgTable [0]["ImageType"].ToString();
context.Response.BinaryWrite((byte[])dtImgTable[0]["Image"]);
}
}
}
public bool IsReusable {
get {
return false;
}
}
You can change the code above by using your own logic.
Now, to use the HttpHandler on your ASP.NET Pages,
<img alt="httpHandler" src="DisplayImage.ashx?id=1">
Conclusion
As you can see from the code sample above, your code is very easy to read if you are using HttpHandler to handle some of the operation on your ASP.NET pages such as displaying images. There are lots more things you can do in HttpHandler to make your code easier to read and maintain. Please leave me a comment if you have any difficulties in understanding the concept of HttpHandler.
No comments:
Post a Comment