C# 在asp mvc中显示数据库中的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/880515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:11:49  来源:igfitidea点击:

Display image from database in asp mvc

c#asp.net-mvc

提问by

I'm getting an image in a byte array format from the controller, How can I display this in the view? in the simplest way.

我从控制器获取字节数组格式的图像,如何在视图中显示它?以最简单的方式。

采纳答案by tvanfosson

Create a controller for displaying images with a Show action that takes the id of the image to display from the database. The action should return a FileResult that contains the image data with the appropriate content type.

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

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

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

In your view, construct the image and use the image id to construct a path for the image using the controller and action.

在您的视图中,构建图像并使用图像 id 使用控制器和动作构建图像的路径。

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

回答by Ropstah

Assuming you have a dataRow (dr) with two columns, "name" and "binary_image" (binary_image contains the binary info)

假设您有一个包含两列的 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(); 

回答by Ropstah

I know this post is rather old but it was one of the first that came up when i was trying to figure out how to do this for the most part Augi answer was correct but most of the assemblies are out dated

我知道这篇文章很旧,但它是第一个出现的,当我试图弄清楚如何做到这一点时,在大多数情况下,Augi 的答案是正确的,但大多数程序集都过时了

  1. i download mvc2 preview 1

  2. no need to worry about the microsoft.web.mvc stuff i couldnt find any of that stuff anyway and search for about an hour trying to figure out what it evolved into

  1. 我下载 mvc2 预览版 1

  2. 无需担心 microsoft.web.mvc 的东西我无论如何都找不到这些东西并搜索了大约一个小时试图弄清楚它演变成什么

this is the code i wrote that works for me for displaying an image from a db field of type image

这是我编写的代码,适用于显示来自图像类型的数据库字段的图像

in my controller class which i called store i have this

在我称之为 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;
}

now for my view page i tried al kinds of ways i found in these forms and nothing worked i am assuming they were just outdated so i tried on a whim the simplest of all thing i could think of and it worked perfectly

现在对于我的视图页面,我尝试了在这些表格中找到的各种方法,但没有任何效果我假设它们已经过时了所以我一时兴起尝试了我能想到的最简单的方法,并且效果很好

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

i kept getting an error from the site about posting img tags so make sure you change the above image to img

我一直从网站上收到关于发布 img 标签的错误,所以请确保将上面的图片更改为 img

hope that helps stop anyone from hunting all day for a current answer

希望这有助于阻止任何人整天寻找当前答案

http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30886

http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30886

回答by farogh haider

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

回答by BrianLegg

The accepted answer of using this:

使用这个的公认答案:

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

is fine, but outdated for mvc 4. The updated syntax should now read:

很好,但对于 mvc 4 来说已经过时了。更新后的语法现在应该是:

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

Also, I find that when I need this functionality I'm already passing other data to the view so it's nice to use the Model instead of the ViewData.

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

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

From your controller:

从您的控制器:

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

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

    return View(model);
}

Finally from your view:

最后从你的角度来看:

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

The "Show" method on the controller for the accepted answer will work but I would change the hardcoded "image/jpg" to use File.ContentType - you can store this along with the byte[] so you don't need to guess if users are uploading their own images.

接受答案的控制器上的“显示”方法将起作用,但我会更改硬编码的“图像/jpg”以使用 File.ContentType - 您可以将其与字节 [] 一起存储,因此您无需猜测是否用户正在上传自己的图像。

回答by Faraz Ahmed

Every answer here may be correct but the simplest way from my opinion is get byte array or Model containing image and simply add like this

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

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