What content type to force download of text response?

I need to stream a file to the Response for saving on the end user’s machine. The file is plain text, so what content type can I use to prevent the text being displayed in the browser?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

To be on the safe side and ensure consistent behavior in all browsers, it’s usually better to use both:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename="My Text File.txt"

Method 2

In most cases, the following should work:

Content-type: application/octet-stream
Content-Disposition: attachment; filename="myfile.txt"

There are some marginal cases of browsers that will still display it as a text file, but none of the mainstream browsers will (I’m talking about browsers embedded in some MIDs).


EDIT: When this answer was originally published, sending the Mime-Type application/octet-stream was the only reliable way to trigger a download in some browsers. Now in 2016, if you do not need to support an ancient browser, you can safely specify the proper mime-type.

Method 3

I don’t think it works that way.

Use a Content-Disposition: attachment header, but stick with the correct Content-Type.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x