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?
Asked
Active
Viewed 5.6k times
3 Answers
31
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\"

Mun
- 14,098
- 11
- 59
- 83
-
5You only need the content disposition, that way you can keep a relevant content type, like text/plain, or whatever. – Matt Connolly Nov 27 '12 at 06:02
-
2@MattConnolly Where do you propose to *keep a relevant content type* if you are not going to use `Content-Type` header? – Piotr Dobrogost Jan 30 '16 at 20:14
-
If I pass this as header from server side, how can front-end use it? I can't use . Let's say if I want use a fetch call. – Ming Huang Jul 15 '20 at 02:45
27
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.

Andrew Moore
- 93,497
- 30
- 163
- 175
-
Do you need to lie about the Content-type? Would be nicer if you could just use Content-Disposition, which /should/ work. – Bobby Jack Oct 09 '08 at 11:55
-
1In my experience, application/octet-stream makes it work more reliably across all browsers. – ceejayoz Oct 09 '08 at 12:01
-
^ What he said. Internet Explorer 6 may still display it as text if text/plain is used. – Andrew Moore Oct 09 '08 at 12:04
-
-
@Shurane: No, it applies to any type of project/language sending data via the HTTP protocol. Use can use [`header()`](http://php.net/header) in PHP to send those. – Andrew Moore Aug 07 '11 at 20:31
-
@PiotrDobrogost: At the time of writing of this answer, `application/octet-stream` was the only way to effectively force a download under IE6. Conditions have changed since then and yes, now, you should use the proper mime-type. – Andrew Moore Feb 02 '16 at 03:41
7
I don't think it works that way.
Use a Content-Disposition: attachment
header, but stick with the correct Content-Type.

Tomalak
- 332,285
- 67
- 532
- 628
-
Only send `Content-Type: application/octet-stream` when User-Agent is Internet Explorer 6... – Bigue Nique Jun 18 '14 at 09:52