如何使用linq在asp:image中显示来自数据库的图像? [英] how to show image from database in asp:image with linq?

查看:70
本文介绍了如何使用linq在asp:image中显示来自数据库的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在数据库中的表:

This is my table in database :

我像这样读取数据库:

DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);

因此,thisuser.picture是图像的句柄.但是如何在页面的asp:image控件中显示它?

So, thisuser.picture is a handle to the image. But how can I show it in asp:image control on my page ?

修改 我用以下代码保存图片:

Edit I save the picture with this code :

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();

有什么问题吗?

推荐答案

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

The ASP.NET Image control loosely represents an <img> tag in HTML. As a result you can only get an image into an HTML doocument by setting the URL to the image content you want to embed in the page.

<img src="images/picture.png" />

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

This means that you need a mechanism to take an HTTP request asking for an image resource, and return a response containing the image binary data.

使用ASP.NET Web API可以轻松实现以下操作:

With ASP.NET Web API this becomes a trivial operation to implement:

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;
}

如果您不能使用Web API,则必须实现HTTP处理程序以完成相同的工作.

If you can't use Web API, you'll have to implement an HTTP Handler to do the same job.

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

In your ASP.NET page, you will have to set the property ImageUrl to the address configured for your controller/handler, including the username as part of the URL.

这篇关于如何使用linq在asp:image中显示来自数据库的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆