File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Servlet -Download Jar file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlet -Download Jar file" Watch "Servlet -Download Jar file" New topic

Servlet -Download Jar file

Karthik Rajendiran
Ranch Hand

Joined: Aug 13, 2004
Posts: 217
Hello Friends,
I am facing some problem in servlet which is written to download files .
I wrote a servlet for downloading jar files. once the user clicks a button or link the servlet is called.


In the above code HelloWorld is my servlet .The code is as follows

I have stored my webapps as d:\tomcat\webapps\karthik
and the a.jar in the d:\tomcat\webapps\karthik path.

when i submit i unable to download the jar , the file i receive is as of unknown format.The file is named HelloWorld.

My web.xml


</servlet-mapping>] [/CODE]

I tried with text files , my text file is opening in the same page without prompting.

Can any one please help me out.

Ben Souther

Joined: Dec 11, 2004
Posts: 13410

MSIE feels no need to obey the content-type header.
Set the Content-Disposition header.
Make sure you use "attachment" and create a file name with a ".jar" extension.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Anil Sadi

Joined: Jan 09, 2001
Posts: 23
Use the following code in your servlet:

import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException

// new code -- start
String filename = request.getParameter("filename");
filename = filename + ".jar";
response.setHeader("Content-Disposition","attachment;filename=\"" + filename + "\"");
// new code -- end

ServletContext ct = getServletContext();
InputStream in = ct.getResourceAsStream("/a.jar");
int read=0;
byte[] bytes = new byte[1024];
OutputStream os = response.getOutputStream();
Karthik Rajendiran
Ranch Hand

Joined: Aug 13, 2004
Posts: 217
Thanks you very much,
It is working ..
As per the Web component developer exam book-kathy sierra,
the code is not working. I couldnt understand why that code in the book is not working.
Then i included the content disposition header which made to work.
When i used the code mentioned by me, the HelloWorld file was downloading instead of the file i requested. May i know the reason for it.

Please explain
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

As I said earlier, MSIE (wrongly) ignores the content-type header sometimes.
It probably works fine in FireFox or any other proper browser.
I agree. Here's the link:
subject: Servlet -Download Jar file
It's not a secret anymore!