Home > Software design >  Return a .zip file containing several .csv files to the browser with ZipOutputStream
Return a .zip file containing several .csv files to the browser with ZipOutputStream

Time:09-01

To begin with, I am well aware that a similar topic is available on Stack OverFlow, but this one does not answer my problem. That's why I'm making this post.

At the moment, my program is able to search for ".csv" files locally, according to certain criteria, to add them to a list, and then to create a file in ".zip" format, which contains all these files. This works without any problem.

Now, I want to download this ".zip" file, from a Web interface, with a button. The connection between the code and the button works, but when I open my downloaded ".zip" file, it contains only one file, and not all the ".csv" files it is supposed to contain. Where can the problem come from?

Here is my code:

FileOutputStream baos = new FileOutputStream("myZip.zip");
ZipOutputStream zos = new ZipOutputStream(baos);
                        
for(String sCurrent : selectedFiles){
    zos.putNextEntry(new ZipEntry(new File(sCurrent).getName()));
    Files.copy(Paths.get(sCurrent), zos);
    zos.closeEntry();
}
zos.close();
response.getOutputStream().flush();
response.getOutputStream().close();

CodePudding user response:

You are closing the ZIP after sending the response. Swap the order:

zos.close();
response.getOutputStream().write(baos.toByteArray());

It would be more efficient if you use try-with-resources to handle close, Files.copy(Paths.get(currentFile), zos); to transfer the files, and if you ZIP straight to the output stream because you might risk out of memory exceptions for large files:

ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

CodePudding user response:

Not an answer so much as consolidation based on @DuncG

            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

            for (String path : selectedFiles) {
                zos.putNextEntry(new ZipEntry(new File(path).getName()));
                Files.copy(Paths.get(path), zos);
                zos.closeEntry();
            }
            zos.close();

  • Related