Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC FileContentResult - prevent opening in browser

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.

like image 761
yoozer8 Avatar asked Oct 05 '11 13:10

yoozer8


1 Answers

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"

like image 198
Ray Avatar answered Oct 23 '22 23:10

Ray