Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC FileStreamResult not working as intended

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.

like image 804
pupeno Avatar asked Jul 13 '09 19:07

pupeno


2 Answers

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.

like image 124
Martin Liversage Avatar answered Nov 07 '22 20:11

Martin Liversage


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" );
like image 12
tvanfosson Avatar answered Nov 07 '22 22:11

tvanfosson