Display byte[] array image from database in Details page template using ASP.NET MVC

旧城冷巷雨未停 提交于 2019-12-06 08:06:00

问题


When I try to display a byte[] array image inside a Details page template using:

public FileContentResult RenderPhoto(byte[] photo)
{
    // var array = (byte[])Session["photo"];
    // return File(array, "image/jpeg");

    return File(photo, "image/jpeg");
}

<img src="@Url.Action("RenderPhoto", Model.Photo)"/>

photo is null.

If I store student.Photo in Session:

//
// GET: /Student/Details/5

public ViewResult Details(int id)
{
    Student student = db.Students.Find(id);

    Session["photo"] = student.Photo;

    return View(student);
}

and try to display the image retrieving the value from Session (commented lines above) it works.

Why I'm getting a null value in the first case?

After passing student to the View in ViewResult Details(int id), Model.Photo doesn't hold that value anymore?


回答1:


Why I'm getting a null value in the first case?

You cannot pass a byte array to the server in an <img> tag. The <img> tag simply sends a GET request to the designated resource. The correct way to do this is to use an id:

<img src="@Url.Action("RenderPhoto", new { photoId = Model.PhotoId })" />

and then:

public ActionResult RenderPhoto(int photoId)
{
    byte[] photo = FetchPhotoFromDb(photoId);
    return File(photo, "image/jpeg");
}



回答2:


First of all

Url.Action("RenderPhoto", Model.Photo)

Will not work, Model.Photo (presumably your byte array) will be treated as an Object to infer route values of. It'll generate a route with the public properties of an Array object, probably along the lines of

?IsFixedSize=true&IsReadOnly=false&Length=255

That is going to be a pretty unhelpful url. Once the page loads in the browser, the browser will request that image, calling your RenderPhoto method, but there is no parameter called photo, so binding would fail, and even if there was a parameter called photo there (AFAIK) no logic in the DefaultModelBinder for creating a byte array from a string, hence photo is null.

What you need to do is pass an anonymous object with an Id property into Url.Action

Url.Action("RenderPhoto", new { Id = Model.PhotoId })

That will be converted to a querystring possibly along the lines of the following (but it depends on your routes)

/xxx/RenderPhoto/25

And you then need to retreive the data for the photo in your RenderPhoto method

Martin



来源:https://stackoverflow.com/questions/5740077/display-byte-array-image-from-database-in-details-page-template-using-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!