Asp.net MVC FileContentResult - 阻止在浏览器中打开
我的控制器操作之一将文件返回给用户。我希望向用户显示下载(打开/保存)对话框,无论文件类型如何。当文件类型为 .doc、.docx、.xlsx 等时,此方法工作正常,但当文件为 .txt、.xps、.pdf(有时)或 .html 时,它会在浏览器中打开。
有没有办法阻止文件在浏览器中打开,并且只允许用户在单独的窗口中打开它,而无需离开当前页面?
文件请求是使用 jQuery 的 $.ajax({})
发出的。
相关:让浏览器处理请求并提供弹出窗口,而不是通过 AJAX 调用接收文件内容作为响应字符串,这个答案,但是这个问题解决了强制浏览器处理收到后以某种方式归档。
One of my controller actions returns a file to the user. I would like the user to be presented with the download (open/save) dialog, regardless of the file type. This works fine when the file type is .doc, .docx, .xlsx, etc.., but when the file is .txt, .xps, .pdf (sometimes), or .html, it opens in the browser.
Is there a way I can prevent the file from opening in the browser, and only allow the user to open it in a separate window without navigating away from the current page?
The request for the file is made using jQuery's $.ajax({})
.
Related: Having the browser handle the request and give the popup as opposed to the AJAX call receiving the conent of the file as a response string is explained by this ansewr, but this question addresses forcing the browser to handle the file in a certain way once it is received.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您无法通过客户端命令或设置来做到这一点。您需要在服务器上执行某些操作,以便它为每个文件返回
application/octet-stream
内容类型。否则,浏览器将查看传入的文件,并根据自己的规则和功能决定如何处理它。如果您可以在服务器上执行此操作,请尝试将
"Content-Disposition"
标头设置为"attachment; filename=whatever.xyz"
I don't think you can do this with a client-side command or setting. You would need to do something on the server so that it returns a content type of
application/octet-stream
for every file. Otherwise, the browser will look at the incoming file and decide what to do with it based on its own rules and capabilities.If you can do this on your server, try setting the
"Content-Disposition"
header to"attachment; filename=whatever.xyz"