There are many scenarios where a web application must serve a file instead of a response containing HTML output to be rendered by the browser.
This little tip illustrates how to cause the browser to display a file download dialog instead of trying to display the data directly (which fails in most cases, especially with binary data).
As you will see, the whole magic concentrates on a special HTTP header, so this tip can be used with any technology and framework, ranging from Java Server Faces (JSF) and the Seam framework to PHP and even ASP or ASP.NET.
A common way to realize file download is to simply write the file data into the HTTP response.
However, if you have to handle arbitrary files, you are not able to set a specific Content-Type header like
text/plain or something else.
So the client (namely the browser) has no idea what kind of data it actually receives and what to do with it.
Here is where the HTTP header Content-Disposition comes into play. Setting this header tells the client that an attachment is received and therefore causes the browser to display a file download dialog.
Now it’s the user’s responsibility to save the file and to open it with a corresponding application.
The Content-Disposition header consists of two values: the string “attachment” indicating an attachment and a “filename” property specifying a filename for the attachment. Usually, the browser takes this value as proposed filename in the download dialog.
The following line is an example extract from an HTTP response containing a Content-Disposition header:
Content-Disposition: attachment; filename="myFile.exe"