ASP.NET MVC 下载图像而不是在浏览器中显示
我不想在浏览器窗口中显示 PNG,而是希望操作结果触发文件下载对话框(您知道打开、另存为等)。我可以使用未知的内容类型使其与下面的代码一起使用,但用户必须在文件名末尾输入 .png 。如何在不强制用户输入文件扩展名的情况下完成此行为?
public ActionResult DownloadAdTemplate(string pathCode)
{
var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));
return base.File(imgPath, "application/unknown");
}
解决方案....
public ActionResult DownloadAdTemplate(string pathCode)
{
var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));
Response.AddHeader("Content-Disposition", "attachment;filename=DealerAdTemplate.png");
Response.WriteFile(imgPath);
Response.End();
return null;
}
Rather than displaying a PNG in the browser window, I'd like the action result to trigger the file download dialogue box (you know the open, save as, etc). I can get this to work with the code below using an unknown content type, but the user then has to type in .png at the end of the file name. How can I accomplish this behavior without forcing the user to type in the file extension?
public ActionResult DownloadAdTemplate(string pathCode)
{
var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));
return base.File(imgPath, "application/unknown");
}
Solution....
public ActionResult DownloadAdTemplate(string pathCode)
{
var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));
Response.AddHeader("Content-Disposition", "attachment;filename=DealerAdTemplate.png");
Response.WriteFile(imgPath);
Response.End();
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我相信您可以使用内容处置标头来控制它。
I believe you can control this with the content-disposition header.
您需要在响应中设置以下标头:
Content-Disposition: Attachment; filename="myfile.png"
内容类型:application/force-download
You need to set the following headers on the response:
Content-Disposition: attachment; filename="myfile.png"
Content-Type: application/force-download
我实际上来这里是因为我正在寻找相反的效果。
I actually came here because I was looking for the opposite effect.
对于 MVC,我使用 FileResult 并返回 文件路径结果
With MVC I use a FileResult and return a FilePathResult
在您的情况下下载文件的正确方法是使用
FileResult
类。The correct way to download file in your case is to use
FileResult
class.实际上,我@7072k3
从我的工作代码中复制了它。
这仍然使用标准的 ActionResult 返回类型。
This I actually @7072k3
Copied that from my working code.
This still uses the standard ActionResult return type.