如何使用 linq 在 asp:image 中显示数据库中的图像?

ham*_*med 6 linq asp.net

这是我在数据库中的表:

在此输入图像描述

我读数据库如下:

DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
Run Code Online (Sandbox Code Playgroud)

所以,thisuser.picture是图像的句柄。但是我怎样才能在我的页面上的 asp:image 控件中显示它呢?

编辑 我用以下代码保存图片:

DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
byte[] filebyte = FileUpload1.FileBytes;
System.Data.Linq.Binary fileBinary = new System.Data.Linq.Binary(filebyte);
thisuser.picture = fileBinary;
db.SubmitChanges();
Run Code Online (Sandbox Code Playgroud)

有什么不对 ?

Pau*_*ner 4

ASP.NETImage控件松散地表示<img>HTML 中的标记。因此,您只能通过将 URL 设置为要嵌入页面中的图像内容来将图像放入 HTML 文档中。

<img src="images/picture.png" />
Run Code Online (Sandbox Code Playgroud)

这意味着您需要一种机制来接受请求图像资源的 HTTP 请求,并返回包含图像二进制数据的响应。

使用 ASP.NET Web API,这变得很容易实现:

public HttpResponseMessage GetImage(string username)
{
    DataClassesDataContext db = new DataClassesDataContext();
    usertable thisuser = db.usertables.FirstOrDefault(
        p => p.username == username);

    if (thisuser == null)
    {
        return new HttpResponseMessage(HttpStatusCode.NotFound)); 
    }

    // Create a stream to return to the user.
    var stream = new MemoryStream(thisuser.picture.ToArray());

    // Compose a response containing the image and return to the user.
    var result = new HttpResponseMessage();

    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
            new MediaTypeHeaderValue("image/jpeg");

    return result;
}
Run Code Online (Sandbox Code Playgroud)

如果您无法使用 Web API,则必须实现 HTTP 处理程序来完成相同的工作。

在 ASP.NET 页面中,您必须将该属性设置ImageUrl为为控制器/处理程序配置的地址,包括将用户名作为 URL 的一部分。