142

I am returning a stream in some response setting the appropriate content-type header. The behavior I'm looking for is this:

  • If the browser is able to render content of the given content type then it should display it in the browser window.

  • If the browser doesn't know how to render the content, then it should display the "save as" dialog where the filename should be the one provided in the response.

The problem is that if I set the Content-Disposition header with:

"attachment; filename="myfile.txt""

the browser will always display the "save as" dialog.

If I don't set Content-Disposition, the filename used in the "save as" dialog is the one in the URL that doesn't work in my case.

I also tried setting Content-Disposition to inline but the outcome is the same.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Hugo Palma
  • 3,376
  • 3
  • 21
  • 22

2 Answers2

200

The correct way could be:

Content-Disposition: inline; filename="myfile.txt"

TehShrike
  • 9,855
  • 2
  • 33
  • 28
Patonza
  • 6,557
  • 5
  • 25
  • 20
  • 9
    I'm not sure what you meant by 'not widely supported' back when you wrote this answer, and wish you'd given hard facts instead of FUD. I just tested in IE 6, IE 8, modern Chrome, and modern Firefox, and it works in all of them; as far as I can tell, it's totally safe to use this nowadays. – Mark Amery Jun 01 '14 at 18:35
  • Does not work with my FireFox 37.0.2 and Internet Explorer 11.0.18. I'm presented with a Save as dialog. Chrome works though. – angularsen May 04 '15 at 09:05
  • 3
    Actually it does work in both Firefox 37.0.2 and IE 11.0.18 (just tested). You are probably using a Content-Type which your browser cannot display inline. – Patonza May 18 '15 at 15:01
  • 2
    A few notes also covered by various discussions over at http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http - if you have spaces in your filename, you need to have double quotes (`"`) around your filename. If you have non-ASCII characters in your filename, you should see that other question for a discussion of what to do. – Christopher Schultz Dec 03 '15 at 18:06
  • Not working for PDF in IE11.0.96. No surprise, Chrome works just fine. – user1566694 Mar 21 '19 at 17:39
2

I'm not sure if that's possible by default. Due to security concerns, browsers don't send all content-types they can handle, but just a few Accept-Encoding, which doesn't help a lot in your scenario.

Maybe you can ask your user what they prefer and store that information in their profile.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162