21

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?

ProfK
  • 49,207
  • 121
  • 399
  • 775

3 Answers3

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
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
  • 1
    In 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
  • This answer isn't particularly asp.net specific, is it? – Ehtesh Choudhury Aug 07 '11 at 20:10
  • @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