ASP.NET MVC FileStreamResult not working as intend

2020-02-09 06:48发布

问题:

I have the following code which I stripped out of any non-essential lines to leave the minimun reproducable case. What I expect is for it to return the image, but it doesn't. As far as I can see it returns an empty file:

public ActionResult Thumbnail(int id) {
    var question = GetQuestion(db, id);
    var image = new Bitmap(question.ImageFullPath);
    MemoryStream stream = new MemoryStream();
    image.Save(stream, ImageFormat.Jpeg);
    return new FileStreamResult(stream, "image/jpeg");
}

Can you identify what's wrong with this code? In the debugger I can see that the stream grows in size so it seems to be getting the data although I haven't been able to verify it's the correct data. I have no idea how to debug the FileStreamResult itself.

回答1:

You need to insert

stream.Seek(0, SeekOrigin.Begin);

after the call to

Image.Save()

This will rewind the stream to the beginning of the saved image. Otherwise the stream will be positioned at the end of the stream and nothing is sent to the receiver.



回答2:

Try rewinding the MemoryStream. The "cursor" is left at the end of the file and there is nothing to read until you "rewind" the stream to the beginning.

 image.Save( stream, ImageFormat.Jpeg );
 stream.Seek( 0, SeekOrigin.Begin );
 return new FileStreamResult( stream, "image/jpeg" );