How do I return a zip file to the browser via the response OutputStream?

16,271

Solution 1

You need to set the Content-Type response header to the value application/zip (or application/octet-stream, depending on the target browser). Additionally, you may want to send additional response headers indicating attachment status and filename.

Solution 2

You need to set the content type header to application/octet-stream prior to streaming the results. Depends on what implementation of response you are using on how you actually do this.

Solution 3

Here is some working code, just in case anyone needs it:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {

        // The zip file you want to download
        File zipFile = new File(zipsResourcesPath + zipFileName);

        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment; filename=" + zipFileName);
        response.setContentLength((int) zipFile.length());

        try {

            FileInputStream fileInputStream = new FileInputStream(zipFile);
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                responseOutputStream.write(bytes);
            }
        } catch (IOException e) {
            logger.error("Exception: " + e);
        }
}

And the HTML:

<a class="btn" href="/path_to_servlet" target="_blank">Download zip</a>

Hope this helps!

Share:
16,271
Bennie
Author by

Bennie

Updated on June 06, 2022

Comments

  • Bennie
    Bennie almost 2 years

    In this situation, I have created a zip file containing search result files, and am trying to send it to the user. Here is the chunk of code I am currently trying to use.

    File[] zippable = new File[files.size()];
    File resultFile = ZipCreator.zip(files.toArray(zippable), results);
    InputStream result = new FileInputStream(resultFile);
    IOUtils.copy(result, response.getOutputStream());
    

    However, this currently doesn't work quite right. Instead of returning the zip file that I have created, it returns an html file. If I manually change the file extension afterwards, I can see that the contents of the file are still the search results that I need. So the problem just lies in returning the proper extension to the response.

    Does anyone have any advice for this situation?