Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileDownloadServlet

 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have written a servlet to download files(files in the my app. include .doc, .pdf, .xsl etc)
My code look similar to this:

response.setHeader("Content-disposition", "attachment; filename=fn" final ServletOutputStream outStream = response.getOutputStream();

final byte[] buffer = new byte[32768];
int n = 0;
while ( ( n = inputStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, n);
}
in.close();
outStream.flush();

This works fine with Internet Explorer(IE 6) i.e., if the file is .doc or .pdf or .xsl then it automatically opens with corresponding applications.

The problem is with Mozilla firefox. firefox tries to open any attachment(.doc, .pdf, .xsl etc) with browser instead of opening with respective applications.

Is there anything we need to set in the servlet so that it knows how to open the attachment.

Thanks in advance
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should be setting the Content-Type header as well.
There is a setContentType convenience method in HttpServletResponse.

Example:
 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ben,

Thanks for your reply. But this way i have to code all possible scenarios
like if the file type is .doc then set content type to
response.setContentType("application/msword");
if type is .pdf then set
response.setContentType("application/pdf"); and so on.......

Is it how my code should look like or is there any other solution for this.
 
Dave Wingate
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way to make the code cleaner is to allow your web container to deduce the appropriate content type based on the file name:



Depending on the server, it may be able to map all of your file names to file types w/o your intervention. But, more than likely, you'll need to add entries to your deployment descriptor like this:



<mime-mapping>
<extension>png</extension>
<mime-type>image/png</mime-type>
</mime-mapping>
 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dave
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic