[Java] Reliable way to download file via Servlet

lozina

Lifer
Sep 10, 2001
11,711
8
81
I'm generating an excel spreadsheet and sending it to a user via Java Servlets. In Firefox everything works great, the user chooses his parameters to generate the file on, then clicks a Submit link. This calls the Servlet which generates the excel and streams it to the user. The user gets a dialog which asks to Open it or Save it. If they choose to Open it, A new instance of Excel opens the file. PErfect.

Now in IE... The user chooses Open and then the browser decides it's going to launch the file itself. The problem is the user now see sall this excel stuff and naturally thinks to click the X to close it, thus closing his session so now to get back to where they were they need to log back in. You'd have to use the Back button.

So what I need to do is get it so that IE opens this file just like Firefox does,and I'm sure it's some tricks with the headers.

I've tried:

response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "filename=report.xls");
response.setHeader( "Cache-Control","" );
response.setHeader("pragma", "");

I've tried also using the octet-stream MIME type, and the Excel specific MIME type.

What's interesting is when I put "attachment;" in front of filename under the Content-Disposition header, IE will actually open up a new Excel instance but for some reaosn the file ends up mangled and Excel can't open it! Not sure why it would do that JUST by modifying the headers...

anyone have any suggestions?

 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
I had to deal with that at a former job. I don't recall if I tracked possible solutions down to the end (probably not, I had to leave a lot of legacy code unchanged) but the way it ended up getting done was browser specific handling. If it was IE, we'd pop up a new window for the file. If it was a netscape variant (yes, the code was that 'legacy'), we'd just let it stay in the same window like you're doing now. That's kind of a nasty hack, because the client may have IE set up to open things externally or someone may someday give firefox the ability to open things like that with plugins.

At any rate, if you were to just do everything in a new window, the worst you'd get would be a blank window left over in firefox. And just for all the opera folk here, try testing there as well :)
 

Argo

Lifer
Apr 8, 2000
10,045
0
0
I've dealt with that in the past. The solution I came up with was to fire the file in a new window. Basically, set the target of your form to _blank.