How do I download a (binary, text, executable) file from a servlet or JSP?

Alex Chaffee

Solution 1: Just use HTTP! This has nothing to do with servlets per se. Make sure the file is on your web server. Then you can either embed a link for your user to click, as

<a href="runme.exe">Click here to download the Runme app</a>
or have your servlet or JSP send a redirect to the file, as
or get fancy with JavaScript (see this FAQ for inspiration).

The point is -- this is still the World Wide Web! HTTP is a file transfer protocol; downloading files what it's for!

Solution 2: Open the file from your servlet using java.io classes, and shove the bytes down the response stream. Make sure to set the content type to match the type of file, e.g. response.setContentType("image/gif") or response.setContentType("application/x-msword"). This technique is a little more expensive, but allows you to do things like security checks, or to access files that are on your web server host, but outside the HTTP directory structure.

For source code to a servlet that "downloads" (actually it's uploading, and the client is downloading, right?) a text file, see this FAQ answer.

Another way to look at it is, there are three directory trees you need to worry about:

  1. webapp
  2. webapp/WEB-INF
  3. the rest of your file system
To download a file from within the webapp, you can use plain old <A HREF> or <IMG SRC>.

To download a file from anywhere else -- including the webapp/WEB-INF under WEB-INF -- you need to call a servlet that opens the file and spits out the contents as described above.

Note that the user your servlet engine is running as must have permission to access that file, or you will get a server error.

See also