开发者

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

开发者 https://www.devze.com 2023-03-16 22:10 出处:网络
I have a fairly simple Action in an MVC3 application that should render an image... public FileStreamResult 开发者_Go百科Photo(int id)

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

  public FileStreamResult 开发者_Go百科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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消