FileResult 返回损坏的文件
我正在 ASP.NET MVC 2(在 .NET 4.0 框架下)创建一个简单的控制器操作,它将调整文件大小。
我有一个像这样的控制器(我已经将其缩小了一点):
public ActionResult GetFile(int fileId, string fileSource) {
FileInfo file = repo.FindFileById(fileId);
//do some resizing
string mimeType = string.Empty;
switch(file.Extension) {
case ".jpg":
mimeType = "image/jpg";
break;
//some more stuff
default:
mimeType = "text/png";
break;
}
return File(file.FullName, mimeType);
}
在文件系统上它保存得很好,我可以查看调整大小的文件,但在浏览器中该文件不会呈现。
我使用 Charles 检查响应,返回的 HTTP 状态为 200,但图像不可见。
如果我尝试保存图像并查看它,Windows 图片查看器会说它已损坏。
我还尝试过使用 ZIP(不调整大小;)),它返回一个损坏的 ZIP 文件。
我确信我只是做错了什么,但我一辈子都无法发现它。
编辑
我已经在 Cassini 和 IIS 7.5 (Windows 7) 中进行了测试,并在这两种情况下都遇到了问题。
I'm creating a simple controller action in ASP.NET MVC 2 (under the .NET 4.0 framework) which will resize files.
I've got a controller like this (I've cut it down a bit):
public ActionResult GetFile(int fileId, string fileSource) {
FileInfo file = repo.FindFileById(fileId);
//do some resizing
string mimeType = string.Empty;
switch(file.Extension) {
case ".jpg":
mimeType = "image/jpg";
break;
//some more stuff
default:
mimeType = "text/png";
break;
}
return File(file.FullName, mimeType);
}
On the file system it saves fine, I can view the resized file, but in the browser the file doesn't render.
I've used Charles to inspect the response and it comes back with a HTTP Status of 200, but the Image isn't visible.
If I try and save the image and view it Windows picture viewer says that it's corrupt.
I've also tried with ZIP (sans resizing ;)) and it returns a corrupt ZIP file.
I'm sure I'm just doing something wrong but I can't for the life of me spot it.
Edit
I've tested in both Cassini and IIS 7.5 (Windows 7) and recieve the problem in both instances.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议您采用排除法。从一个简单的操作和一个有效的 jpeg 图像开始:
如果这不起作用,那么您可能遇到了其他问题(您也可以尝试清除浏览器缓存)。如果它有效,请在调整大小等之前将
test.jpg
替换为您拥有的文件,直到找到问题为止。I would recommend you to proceed by elimination. Start with a simple action and a working jpeg image:
If this doesn't work then you might be having some other problem (you might also try clearing the browser cache). If it works replace the
test.jpg
by the one you have but before resizing, etc, until you find the problem.事实证明,问题是由网站上运行的 Http 压缩模块引起的,它试图转换图像响应,从而损坏图像。
It turns out the problem is caused by a Http Compression module which is running on the site, it's trying to transform the image response, corrupting the image.
jpeg 的正确 mime 类型是 image/jpeg,而不是 image/jpg。这会引起问题。
您还应该发布调整大小的代码,因为这可能是导致损坏的原因。如果您只是阅读罚款并将其写回会发生什么?
The correct mime type for a jpeg is image/jpeg, not image/jpg. This will cause issues.
You should also post your resizing code as this is likely the cause of your corruption. What happens if you just read the fine and write it back out?
尝试使用 FileResult 而不是 ActionResult
Try using FileResult instead of ActionResult