ASP.NET MVC FileStreamResult not working as intended

白昼怎懂夜的黑 提交于 2019-11-27 15:38:00

问题


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" );


来源:https://stackoverflow.com/questions/1121703/asp-net-mvc-filestreamresult-not-working-as-intended

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