The moose likes Servlets and the fly likes FileDownloadServlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "FileDownloadServlet" Watch "FileDownloadServlet" New topic


Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228

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 = != -1)
outStream.write(buffer, 0, n);

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

Joined: Dec 11, 2004
Posts: 13410

You should be setting the Content-Type header as well.
There is a setContentType convenience method in HttpServletResponse.


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

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
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:


Fun programming etcetera!
Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
Thanks Dave
I agree. Here's the link:
subject: FileDownloadServlet
It's not a secret anymore!