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

痞子三分冷 提交于 2019-11-27 09:33:30
JoshBerke

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.

Here is some example code on how to do this.

I wrote the SqlReader plugin for open-source ImageResizing.Net library to allow you to serve and display images from a SQL database in the most performance-optimal way.

Even if you don't need to do any image processing whatsoever, it's still (a) the easiest, and (b) the most efficient way to do it. You can combine it with disk caching (which provides automatic cleanup) to get the best performance that is possible.

Installation is easy - 2 nuget commands, or copy & paste into Web.Config, your pick.

If you need help, support is free and fast.

Sruly

The sample code you added is good but you should move it to a .ashx file which is meant for such things.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!