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();
String dateString = formatter.format(objDate.getTime());

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

res.setHeader("Content-Disposition", "attachment;filename="+filename+";");