How do I download a (binary, text, executable) file from a servlet or JSP?
Created Feb 1, 2000
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
response.sendRedirect("http://myserver.com/files/runme.exe");
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!
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:
- webapp
- webapp/WEB-INF
- the rest of your file system
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