0

I have a java servlet that uses ServletOutputStream to stream binary files from the application server to a browser. The code that does this has been in prod for a rather long time, and works really well the vast majority of the time. My users are reporting an odd problem that only happens in firefox. After the ServletOutputStream finishes sending the file, firefox displays the file in the standard firefox window as jibberish strings of text, as opposed to prompting the user to select the application they would like to use. This doesn't consistently happen with any one file or file type. I have personally seen it happen once, but when I tried to download the file again, it worked correctly. A few users using firefox report the problem more frequently. Unfortunately no exceptions are being thrown to any logs, and I can't seem to reproduce it confidently at all.

The application is running on Java 6 and tomcat 6, and is fronted by apache. Any ideas on what could be going on, or how to troubleshoot this?

The code:

File target = file.getAttachment();
response.setContentType(file.getMimeType());
response.setContentLength(new Long(file.getFileSize()).intValue());
response.addHeader("Content-Disposition", "attachment; filename=" + file.getFileName() + ".foo;");
response.addHeader("Cache-Control", "max-age=0");
ServletOutputStream stream=response.getOutputStream();
BufferedInputStream fif=new BufferedInputStream(new FileInputStream(target));
int data;
int counter = 0;
try {
  while((data=fif.read())!=-1) {

    stream.write(data);
    //System.err.println("A   counter: " + counter);
    counter++;
    //if (counter > 249000) {
        //throw new Exception("Foo this bar!");
    //}
  }
  System.err.println("counter: " + counter);
} catch(SocketException x) {
  // catch socket reset by peer errors here, and ignore them.
  x.printStackTrace();
}
fif.close();
stream.close();
Jay
  • 4,994
  • 4
  • 28
  • 41
  • What headers does your servlet set on the response? – watery Feb 22 '14 at 01:02
  • I edited to include the code. Does that answer your question? – Jay Feb 22 '14 at 01:50
  • The only thing I could think of is that sometimes that `file.getMimeType()` isn't returning the expected filetype for the file, or that in Firefox settings (in Options -> applicatons) a specific file type has been set to be opened inside the browser. – watery Feb 22 '14 at 10:06
  • How can I determine if file.getMimeType() isn't returning what I expect it to? I am having trouble reproducing this, and doesn't appear to consistently happen for users on campus, even with the same file. – Jay Feb 24 '14 at 13:21
  • I've no idea, it depends on the class of your `file` instance (I once had a similar problem, but the MIME type was provided by a framework) - I guess only logging could help there. Does it at least happen with the same user and the same file? – watery Feb 25 '14 at 18:33

0 Answers0