views:

1217

answers:

3

I have run into an issue in which IE does not open up the Save As/Open dialog box for an Excel document like Firefox does.

So I have created a servlet filter that is using '*.xls' as the url pattern. The issue that I now face (since this is the first filter I have created) is how to get the name of the file that the user wants so that the dialog box gets populated correctly. Currently the filter is invoked when the user selects a link on a given page.

Here is what I came up with:

The above is what I have doFilter().

String fileName = "fileName.xls";

HttpServletRequest httpRequest = (HttpServletRequest) pRequest;
String requestURI = httpRequest.getRequestURI();

if(StringUtils.isNotBlank(requestURI))
{
  String uri[] = StringUtils.split(requestURI, '/');
  fileName = uri[uri.length - 1];
}

HttpServletResponse httpResponse = (HttpServletResponse) pResponse;
httpResponse.setContentType("application/vnd.ms-excel");
httpResponse.setHeader("Content-disposition", "attachment; filename=\"" + fileName +"\"");

web.xml:

<filter>
    <filter-name>ExcelFilter</filter-name>
    <filter-class>vsg.rp.common.ExcelFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>ExcelFilter</filter-name>
    <url-pattern>*.xls</url-pattern>
</filter-mapping>

This all is working on my development box: Windows XP, JBoss, Eclipse, Oracle. But when it runs on the test server—Linux, Apache/JBoss, Oracle—it does not work. It appears that the filter is not even being called, no errors thrown, etc. Any idea as to why this would happen?

+1  A: 

Use the Content-Disposition HTTP header and set it to something like:

attachment; filename=myworkbook.xls

The is a Microsoft Knowledge Base Article all about this problem. And here is an example of setting Content-Disposition in Java code.

Dave Webb
+5  A: 

You want the content type set appropriately as well as the content disposition header, thus:

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

Brian Agnew
You indicate a filename variable - how does this get set?
boyd4715
That's just the name of the file as you want it to be presented to you in the browser. e.g. setting filename="sample.xls" will prompt IE/Firefox etc. to download the Excel and save it (if required) as "sample.xls"
Brian Agnew
A: 

In addition to setting the headers for the content type, you'll also want to ensure that the server DOES NOT tell the browser to NOT CACHE the file.

In IE land, if you tell IE not to cache the file, it happily downloads the file... then tries to open the file from the directory it saved the file to... However since the headers said "don't cache" it takes this literally, and doesn't save the file, thus Excel throws an error saying, "There is no file!".

Long story short, tell IE to CACHE the file.

scunliffe