Thursday, March 29, 2007

How to always force a download of a file

Here's a way in Java of how to force a file to download instead of opening it up with the associated program. Firefox is OK, the problem usually shows up in IE. The main thing is setting the right header Content-Disposition and content type. Also included is a workaround for a weird bug found in IE if you're in https.


/* patch for IE SSL mode. */
SimpleDateFormat formatter = new SimpleDateFormat ("EEE, dd MMM yyyyHH:mm:ss zzz");
Calendar objDate = GregorianCalendar.getInstance();
objDate.add(objDate.MINUTE,1);
String dateString = formatter.format(objDate.getTime());

res.setHeader("Expires", dateString);
res.setHeader("Cache-Control","store, cache");
res.setHeader("Pragma","cache");
/* end patch */

res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename="+filename+";");

1 Comments:

Anonymous Marilu said...

Thanks for writing this.

5:52 PM  

Post a Comment

Links to this post:

Create a Link

<< Home