| Author |
FileDownloadServlet
|
Saathvik Reddy
Ranch Hand
Joined: Jun 03, 2005
Posts: 228
|
|
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
Joined: Dec 11, 2004
Posts: 13410
|
|
You should be setting the Content-Type header as well. There is a setContentType convenience method in HttpServletResponse. Example:
|
Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
|
 |
Saathvik Reddy
Ranch Hand
Joined: Jun 03, 2005
Posts: 228
|
|
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
Joined: Mar 26, 2002
Posts: 262
|
|
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>
|
Fun programming etcetera!
|
 |
Saathvik Reddy
Ranch Hand
Joined: Jun 03, 2005
Posts: 228
|
|
Thanks Dave
|
 |
 |
|
|
subject: FileDownloadServlet
|
|
|