Wednesday, October 5, 2011

Forcing SaveAs using the HTTP header

Forcing SaveAs using the HTTP header


In order to force the browser to show SaveAs dialog when clicking a hyperlink you have to include the following header in HTTP response of the file to be downloaded:

Content-Disposition: attachment; filename=<file name.ext>

Where <file name.ext> is the filename you want to appear in SaveAs dialog (like finances.xls or mortgage.pdf) - without < and > symbols.

You have to keep the following in mind:
  • The filename should be in US-ASCII charset.
  • The filename should not have any directory path information specified.
  • The filename should not be enclosed in double quotes even though most browsers will support it.
  • Content-Type header should be before Content-Disposition.
  • Content-Type header should refer to an unknown MIME type (at least until the older browsers go away).
There is something more about it, you must read

THIS

before you use this header.

3 comments:

  1. If you do not want the open/save dialog box to appear,
    do not give attachment; in the value of Content-Disposition. Only give the filename.

    And you might need to do some setting in your browser as given on the following URL.

    http://www.shaunakelly.com/word/sharing/opendocinie.html

    ReplyDelete
  2. Please note that this code will not give work properly on google chrome, though it works fine on IE.

    The problem on google Chrome is that the file name does not appears.

    I used

    response.setHeader("Content-Disposition: ", "attachment; filename=" + targetFile.getName());

    ReplyDelete