FileStreamResult displays empty browser document when rendering image from stream in MVC3

北慕城南 提交于 2019-12-22 00:32:10

问题


I have a fairly simple Action in an MVC3 application that should render an image...

  public FileStreamResult Photo(int id)
    {
        //get the raw bytes for the photo
        var qry = from p in db.Photos
                  where p.PhotoID == id
                  select p.PhotoData;
        var data = qry.FirstOrDefault();

        var mem = new MemoryStream(data);
        var fs = new  FileStreamResult(mem, "image/jpeg");
        return fs;
    }

When i run this i get a blank document in Chrome, Firefox displays the URL in the actual document area and IE renders the raw bytes.

Chrome gives me a message: Resource interpreted as Document but transferred with MIME type image/jpeg

This suggests to me that the stream data is not being sent to the browser and it is in fact receiving an empty document, but IE suggests the opposite.

Anyone come across this before, or know how to get around it?


回答1:


You don't need a stream if you already have a byte array of the photo:

public ActionResult Photo(int id)
{
    var data = db.Photos.FirstOrDefault(p => p.PhotoID == id);
    if (data == null)
    {
        return HttpNotFound();
    }
    return File(data.PhotoData, "image/jpeg");
}

The problem with your code is that you need to reset the memory stream at the beginning but as I said you don't need all this.



来源:https://stackoverflow.com/questions/6567966/filestreamresult-displays-empty-browser-document-when-rendering-image-from-strea

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