0

我正在使用 ASP.NET 制作照片库。我将用户的图像存储在 SQL 数据库中。我不知道应该如何显示图像。

假设每个用户有 1 张图片,我正在做这样的事情:

  • 从数据库中获取图像
  • 将其保存在服务器的磁盘上为“file.jpg”
  • ASP:Image.uri = "文件.jpg"

这一直很好,直到我发现如果很少有用户同时加载该页面,它可能无法正常工作。

然后我虽然将“file.jpg”更改为一些随机字符串会对我有所帮助:

  • 从数据库中获取图像
  • 以“ABCDUDHDJSAKFHADGJKHAKADFAD.jpg”的形式保存在服务器的光盘上
  • ASP:Image.uri = "ABCDUDHDJSAKFHADGJKHAKADFAD.jpg"
  • File.Delete("~/ABCDUDHDJSAKFHADGJKHAKADFAD.jpg");

但无法删除此文件,因为它仍在被服务器使用。

解决我的问题的正确方法是什么?我的照片库中的用户最终会同时看到 12 张照片。

4

2 回答 2

0

What I usually do is serve images from DB using a generic handler (ashx file).

What you need to do is create an ashx file and use something along these lines:

context.Response.BinaryWrite(myImage);

The you create image tags like so:

<img alt="whatever" src="/images.ashx?iid=1243 />

Where iid is the unique ID of the image in the DB.

于 2013-04-07T12:59:31.610 回答
0

您实际上不应该存储该文件。你应该流它。例如,创建一个处理程序,它从具有特定 ID 的用户返回图像并使用该 ID 调用它,例如image.ashx?id=1. 处理程序可能看起来像

Image image; // image from your database
using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    ms.WriteTo(context.Response.OutputStream);
}
Response.ContentType = "image/png";

您可以像使用静态图像文件一样使用此处理程序。因此,您甚至可以将其用于background-image

<div style="background-image: url(image.ashx?id=1)">Username</div>
于 2013-04-07T12:57:29.820 回答