Download zip from Java Servlet

I don't understand why it is so difficult and each has its own implementation ...

So, on my server, I create a file .zip

that I want the user to be able to download on click.

So, I set up a request that the server received successfully and now I am afraid of writing a byte array in the output.

Here's my code for the answer:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("Downloading clusters.zip");

        /* Generate the directory on the server, then zip it. */
        clustersToFiles();
        zipClusters();
        /* Now the zip is saved on zipFullPath */

        System.out.println("Done generating the .zip");

        String parent_dir = System.getProperty("catalina.base");
        String filename = "clusters.zip";
        String zipFullPath = parent_dir + "/" + filename;

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        OutputStream out = response.getOutputStream();

        FileInputStream fis = new FileInputStream(zipFullPath);
        int bytes;
        while ((bytes = fis.read()) != -1) {
            System.out.println(bytes);
            out.write(bytes);
        }
        fis.close();
        response.flushBuffer();

        System.out.println(".zip file downloaded at client successfully");
}

      

+3


source to share


1 answer


The fact that the downloaded file is a ZIP doesn't matter (other than the content type), you just want to download the binary.

PrintWriter

is not suitable, this script is used to write text output and the method used write(int)

:

Writes one character ...

Just use a simple OutputStream

low level, his method write(int)

:



Writes the specified byte to this output stream.

So, simply:

OutputStream out = response.getOutputStream();

      

You can find a few more ways to do this in this question: Implementing a Simple Servlet Load File

+4


source







All Articles