force browser to download a file
Posted by Stefan Camilleri on {2008.July.30}
/** A common problem which I have come across multiple times in the past is that of forcing a browser (any browser) to download a file rather than try to open it. */
There’s a myriad of solutions out there on the web discussing this very issue, and I never gave much thought to it until yesterday. {
I came across an excrept of code at my client which was trying to send a csv file to the client (i.e. the client pc), yet the browser (all flavours) insisted on trying to render it, rather than download it.
The solution turned out to be particularly simple; something we all learnt how to do very well when we wanted some sweets as kids… i.e. LIE (to the browser this time)
All you have to do is set the content type to application/binary and the browser will simply not bother trying to do anything with it.
Here’s the magic expression in Java, yet of course this also applies to any other lingo (and if you have a problem, ask me, tell me your language, and if I can, I’ll show you how).
response.setContentType("application/binary");NOTE: IE works slightly different from other browsers (what's new?), in that if you cancel the download, it will close the socket throwing an exception on the server. You of course will need to cater for this.
}
David Keaveny said
Isn’t it better to leave the mime type as it should be, and set the content-disposition?
Content-Type: text/comma-separated-values
Content-Disposition: inline; filename=openinexcel.csv
IIRC if you set the Content-Disposition to attachment, rather than inline, it’ll bring up the download prompt.