Thursday, December 27, 2012

Hosting images using Handler (ASHX)

In HTML, when we want to display images, we are using the following tag:

   <img src="images/myProfilePhoto.jpg"/>

That's very simple and has nothing much to complaint. But, you won't be able to trace who has requested the image file especially when the privacy issue comes into place... it becomes very nasty. In this case, we need to use ASP.NET Handler (ASHX) to host the images.

Advantage of hosting images through Handler:
  • You can hide the image file path. For example, your web app is located in D drive and all image files are stored in E drive (where you don't have to expose the image folder in IIS).
  • You may track down the visitor information that includes their IP address, browser, etc.
  • You may stored the images in a database and host it through the Handler - you don't need to create an image file physically and then write the phyicsal file name into "SRC" attribute. You just need to set the SRC attribute to your ASHX handler (refers to the sample code in the link below).
  • You may cache the images in the server.

In the HTML, you will have something like this:

  <img src="showPhoto.ashx?memberID=0001"/>

Where "showPhoto.ashx" is the Handler that you develop and "memberID" is the query parameter. Your handler should return the profile photo (in byte array) for member ID 0001.

For the code on how to implement the Handler or ASHX:

  http://stackoverflow.com/questions/994135/image-from-httphandler-wont-cache-in-browser
  http://stackoverflow.com/questions/1507572/streaming-databased-images-using-httphandler

For full explanations on the Handler:

   http://support.microsoft.com/kb/308001

No comments:

Post a Comment