在ASP MVC中从数据库显示图像

67

我从控制器中以byte数组的方式获取了一张图片,如何以最简单的方式在视图中显示它?


请查看此示例:http://www.codingfusion.com/Post/Display-Image-from-Database-in-ASP-NET-MVC - undefined
6个回答

125

创建一个控制器,用于显示图片,其中包含一个Show操作,该操作从数据库中获取要显示的图像的ID。该操作应返回一个FileResult,其中包含具有适当内容类型的图像数据。

public class ImageController : Controller
{
    public ActionResult Show( int id )
    {
        var imageData = ...get bytes from database...

        return File( imageData, "image/jpg" );
    }
}

根据您的视角构建图像,并使用图像id使用控制器和操作构建图像路径。

<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>' />

1
错误:无法创建静态类“System.IO.File”的实例。 - Jeremy Knees
1
@JeremyKnees 这个类应该从 Controller 派生(已经修复)。FileController 上的一个方法。 - tvanfosson
如果您正在使用HomeController,那么ActionResult Show()在View中应该返回什么? - Moojjoo

11

使用以下方法作为最佳答案:

<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>'

现在的MVC 4已经更新了语法,原来的语法也可以使用,但已经过时。

<img src='@Url.Action( "show", "image", new { id = ViewData["imageID"] })' />

此外,我发现当我需要这个功能时,我已经将其他数据传递给视图,因此使用模型而不是ViewData更好。

public class MyModel {
    public string SomeData {get;set;}
    public int FileId {get; set;}
}

来自您的控制器:

public ActionResult Index() {
    MyEntity entity = fetchEntity();

    MyModel model = new MyModel {
        SomeData = entity.Data,
        FileId = entity.SomeFile.ID
    };

    return View(model);
}

最后从您的角度来看:

<img src='@Url.Action("show", "image", new { id = Model.FileId })' />

对于采纳答案的控制器,“Show”方法是可行的,但我会更改硬编码的“image/jpg”以使用File.ContentType - 您可以将其与byte []一起存储,因此无需猜测用户是否正在上传自己的图像。


6

这里的每个答案都可能是正确的,但我认为最简单的方法是获取包含图像的字节数组或模型,然后像这样简单地添加:

<img  src="data:image/jpeg;base64,@(Convert.ToBase64String(Model.Picture))">

完美解决方案。非常感谢。 - user11974227

4
我知道这篇帖子有点老了,但当我试图弄清楚如何做到这一点时,它是最早出现的之一。大部分时间Augi的答案是正确的,但大多数程序集已过时。
  1. 我下载了mvc2预览版1

  2. 不必担心Microsoft.Web.Mvc的问题,因为我无法找到任何有关该问题的信息,并且花费了一个小时左右来寻找它的演变方式。

以下是我编写的代码,实现从数据库字段类型image中显示图像:

在我的控制器类(命名为store)中,我有以下代码:

public ActionResult GetImage(int id)
{
    byte[] imageData = storeRepository.ReturnImage(id);

    //instead of what augi wrote using the binarystreamresult this was the closest thing i found so i am assuming that this is what it evolved into 
    return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}

//in my repository class where i have all the methods for accessing data i have this

public byte[] ReturnImage(int id)
{
    // i tried his way of selecting the right record and preforming the toArray method in the return statment 
    // but it kept giving me an error about converting linq.binary to byte[] tried a cast that didnt work so i came up with this
    byte[] imageData = GetProduct(id).ProductImage.ToArray();
    return imageData;
}

现在,对于我的视图页面,我尝试了这些论坛中找到的各种方法,但都不起作用。我认为它们可能已经过时了。所以,我随便尝试了最简单的方法,结果完美解决了问题。

<image src='/store/getimage/<%= Html.Encode(Model.productID) %>' alt="" />

我一直从网站上收到有关发布img标记的错误提示,所以请确保将上面的图像更改为img。希望这能帮助停止任何人整天寻找当前的答案。 http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30886

2
public ActionResult EmployeeImage(int id)
{
    byte[] imageData ="Retrieve your Byte[] data from database";
    if (imageData!= null && imageData.Length > 0)
    {
        return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
    }
}

-2
假设您有一个名为dataRow(dr)的数据行,其中包含两列,“name”和“binary_image”(binary_image包含二进制信息)。
 Byte[] bytes = (Byte[])dr["Data"];
 Response.Buffer = true;
 Response.Charset = "";

 Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.ContentType = dr["Image/JPEG"].ToString();

 Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows[0]["Name"].ToString());

 Response.BinaryWrite(bytes);
 Response.Flush();
 Response.End(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接