7

I use this code in a Servlet which sets the file name of the inlined PDF document:

response.setContentType("application/pdf");
response.setContentLength((int) file.length());
response.setHeader("Content-disposition", "inline; filename=\"" + file.getName() + "\"");

However this does not work in IE 9: the "Save as..." Dialog shows only the last path part of the URL followed by ".pdf" (for "/some/url/invoice" it is "invoice.pdf")

Is this a known bug? Is there a workaround?

mjn
  • 36,362
  • 28
  • 176
  • 378
  • What does "this does not work" mean exactly in this context - what name are you getting instead? What kind of name did you try to set, can you make an example? – Pekka Jan 16 '12 at 10:26
  • Try without placing quotes or by using single quotes around the filename – Valamas Jan 16 '12 at 10:27
  • Possible duplicate of http://stackoverflow.com/questions/151079/name-web-pdf-for-better-default-save-filename-in-acrobat – mjn Jan 16 '12 at 10:41

1 Answers1

13

That's indeed default behaviour of IE. It does not use the filename attribute of the Content-Disposition header in any way to prepare a default filename for the Save As. Instead, it uses the last part of the request URL path info.

I recommend rewriting your Servlet and/or the links in such way that the desired filename is supplied as part of request path info instead of as for example a request parameter.

So, instead of

<a href="/pdfservlet">View PDF</a>

or

<a href="/pdfservlet?file=foo.pdf">View PDF</a>

you need to use

<a href="/pdfservlet/foo.pdf">View PDF</a>

When mapped on an URL pattern of /pdfservlet/*, you can if necessary grab the filename part dynamically in the servlet as follows (for example, to locate the desired PDF file and/or to set the right filename in the header for the more decent webbrowsers):

String filename = request.getPathInfo().substring(1); // foo.pdf

This is by the way regardless of whether it's served inline or as an attachment.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Is this the case for IE10+? – Jeremy Ray Brown Apr 23 '15 at 19:48
  • This seems to be the case for IE 11 too. Any work-aroundd that does not change the URL so far? When using "attachment" as download-type it is working fine. The table @ http://greenbytes.de/tech/tc2231/ also says that inline is broken for IE. Anyone has a table that includes IE 10/11? – rominator007 Feb 10 '16 at 15:46
  • @rominator007: See first paragraph why such workaround is impossible. – BalusC Feb 10 '16 at 15:49
  • @BalusC Yeah. I read that. Thank you. I just wanted to know if one could bring IE 10+ to another behavior since the question is quite outdated. Unfortunately that does not seem to be the case :-( – rominator007 Feb 11 '16 at 19:03
  • For all which have issue's in C#/Asp.net with the point in the url check this link: https://stackoverflow.com/a/21000255/7302498 – Astrophage Oct 25 '17 at 08:40