This article aims at presenting how to create a servlet that sends a zip file to the user. We create here a html page with a form where you can enter an url. The servlet will get the content of this url (only the html page, not the images or other frames), create a zip file with it, and send you the file.
This example can be used as a basis to do various things.

  • Sending a file with a servlet
    This involves two headers: Content-Type and Content-Disposition. The content type is set to “application/zip”. The other one is used to specify the filename used by the browser when it starts downloading the file.

    res.setContentType("application/zip");
    res.setHeader("Content-Disposition","inline; filename=output.zip;");
    

    This header replace “res.setHeader(“Content-Disposition”,”attachment; filename=output.zip;”);” (not work with IE5)

    In this example, we create a zip file. We’ll discuss later on how to create such files. As soon as we get a byte array with the zip file, we are ready to send it.
    We simply call out.println(zip) to send the file.

  • li>Creating a zip file Have you ever noticed the java.util.zip package ?
    Basically, a zip file is created by adding ZipEntries to a ZipOutputStream.
    Once we have create a ZipEntry with a file name, we are ready to write an array of byte to the ZipOutputStream. Then we close the entry, finish the work with a call to finish(). We finally get a String containing the zipped file.

    zout.putNextEntry(new ZipEntry("file.html"));
    zout.write(b,0,size);
    zout.closeEntry();
    zout.finish();
    String zip=bout.toString();
    

    (more…)