Wednesday, December 3, 2008

HTTP: Forcing download

There are some content types, other than HTML, that web browsers can render, like images, XML, and pdf. When an HTTP response is received, having a content-type from those, the default behaviour of most browsers is to render it, not to download it. To make a browser understand that the response is to be downloaded, not rendered, you must be explicit about it.

Now, how do you do it? There is a standard HTTP response header that many people just don't know about. It's called 'content-disposition'. It's default value for most browsers is 'inline', which causes the browser to render instead of download. To force download, you must specify that your content-disposition' is 'attachment'. You can also add a file name to the downloaded file:
Content-disposition: attachment; filename=name.ext

This way, the browser will understand that the response body is to be downloaded instead of rendered, even if it's a known type that can be rendered.

No comments: