ASP.NET MVC FileStreamResult 未按预期工作

发布于 2024-07-26 16:50:21 字数 481 浏览 2 评论 0原文

我有以下代码,我删除了任何非必要的行,以留下最小的可重现情况。 我期望它返回图像,但它没有。 据我所知,它返回一个空文件:

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

你能确定这段代码有什么问题吗? 在调试器中,我可以看到流的大小不断增大,因此它似乎正在获取数据,尽管我无法验证它是正确的数据。 我不知道如何调试 FileStreamResult 本身。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

許願樹丅啲祈禱 2024-08-02 16:50:21

您需要

stream.Seek(0, SeekOrigin.Begin);

在调用后

Image.Save()

插入,这会将流倒回到已保存图像的开头。 否则,流将位于流的末尾,并且不会向接收者发送任何内容。

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.

只等公子 2024-08-02 16:50:21

尝试倒回 MemoryStream。 “光标”留在文件的末尾,并且在您将流“倒回”到开头之前没有任何内容可读取。

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

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" );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文