What’s the best way to display an image from a sql server database in asp.net?

Two options:

Create a temp file – The problem with this approach is that you have to create the file, which means your web must have write access to a directory which is not a great thing. You also need to have a way to clean up the images.

Serve it from another URL – This is my preferred method, as you have no disk access required. A simple http handler (ashx) is a great method to serve up the image.

Edit

If you need session state in the ashx, check out: Asp.net System.Web.HttpContext.Current.Session null in global.asax.

Edit

Couple more thoughts. There are some cases where using a temp file might be better. For example if your images are requested frequently by a lot of users. Then storing the images on the disk would make sense, since you could write the file once, this does increase the maintance complexity but depending on traffic it might be worth it since this would let you avoid calling back into the .net stack and leverage IIS caching of static content.

Leave a Comment