Asp.net MVC FileContentResult - prevent opening in browser

£可爱£侵袭症+ 提交于 2019-12-13 13:13:22

问题


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.


回答1:


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"



来源:https://stackoverflow.com/questions/7662363/asp-net-mvc-filecontentresult-prevent-opening-in-browser

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