Thursday, May 21, 2009

Directly download a file by pressing a link using Java Servlet

There are times in which we would like to directly download a resource by pressing on a link on a page. The meaning of directly is:
  • The browser dialog will be open asking where to save the resource.
  • After saving the file the browser will stay on the same page without doing any refresh or opening a child window.

Usually this is useful if we would like to allow the user to download some real time dynamically generated file that is being created on the server side.
For the example we will use the ZipDir class from this post. We will see how we can allow the user download a dynamically created zip file by pressing on a link.

In general, in order to achieve the above behavior we have to instruct the response with 2 instructions:

  • Set the response content type to: “application/zip”. This is in the case of sending back to the client a Zip file. For any other file type we should set the correct content type. For example, if we would like to send back to the client a PDF file the following content type should be used: “application/pdf”.
  • Set response header: “Content-disposition” with the following value: “attachment; filename=<filename>”, where filename is the name of the file we want the user to see in the “save” dialog.

Here is an example of a Servlet that generates a Zip file on the fly and sends it back to the browser:

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ZipServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Content-disposition", "attachment;");
    ServletOutputStream outputStream = response.getOutputStream();
    new ZipDir("/somedir", outputStream).zip();

Note that our ZipDir class is smart enough to set the generated Zip file directly to the output stream of the response. That is a neat solution saving us from needing to generate temporary Zip files on the server that later will have to be deleted.

Nothing special on the web.xml file, just define a Servlet, with “zip” url pattern:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""
      <servlet-name>Zip Servlet</servlet-name>
      <servlet-name>Zip Servlet</servlet-name>

And finally, a sample HTML page with a download link to the Zip resource:

  <title> Zip Download Sample Page </title>
 <h3>Zip download sample page</h3>
 Press this link: <a href="zip">Download Zip resource</a>
Note that we call “zip” Servlet directly as a relative path to the server context.

No comments:

Post a Comment