我在SQL Server数据库中存储了一个图片,并与用户数据一起检索出来。
现在我直接在页面上拥有了byte[]。我该如何将它放入WebControls.Image中?我不想调用HttpHandler并再次调用数据库。
显然,这只是将它输出到整个页面。
Context.Response.BinaryWrite(user.Picture.ToArray());
我在SQL Server数据库中存储了一个图片,并与用户数据一起检索出来。
现在我直接在页面上拥有了byte[]。我该如何将它放入WebControls.Image中?我不想调用HttpHandler并再次调用数据库。
显然,这只是将它输出到整个页面。
Context.Response.BinaryWrite(user.Picture.ToArray());
将字节数组包装在MemoryStream对象中,并将其放置在ASP.NET的缓存中。
MemoryStream ms = new MemoryStream(user.Picture.ToArray());
Guid imageGuid = new Guid();
HttpRuntime.Cache.Add(imageGuid.ToString(), ms, null,
DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
string imageGuid = context.Request.QueryString[image];
MemoryStream ms = (MemoryStream)HttpRuntime.Cache[imageGuid];
// configure context.Response with appropriate content type and cache settings
// ** Edit **
// It seems I need to be more explicit with regard to the above comment:-
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetLastModified(DateTime.UtcNow);
context.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(2);
context.Response.Cache.SetMaxAge(TimeSpan.FromHours(2));
context.Response.Cache.SetValidUntilExpires(true);
ms.WriteTo(context.Response.OutputStream);
HttpRuntime.Cache.Remove(imageGuid);
If-Modified-Since
、缓存等)和可扩展性,却没有任何好处。 - Anton Gogolev<img src="image.aspx?id=number" >
number是数据库中图像的ID
ashx
,虽然我同意这是正确的做法。(而且创建一个aspx
也不比创建一个ashx
容易!) - LukeH<img>
以显示该图像而不重新查询数据库? - AnthonyWJonesashx
处理程序中)查询一次即可。 - LukeH我非常确定您不能在页面本身中执行此操作。
如果您不想创建HTTP处理程序来输出图像,则替代方法是创建一个单独的aspx
页面。将img
标记的src
设置为指向该页面,通过查询字符串传递某种ID,以便可以从数据库中提取图像数据。
话虽如此,设置aspx
页面来执行此操作并不比设置ashx
更快或更容易。我建议按照正确的方式进行操作,并创建HTTP处理程序。