Hello friends,
I am stuck at a point in downloading multiple files as a single zip such that - the generated zip by my code for user download seems to be not a properly formed one. While trying to open the generated zip, I get an error as - "Cannot open file: it does not appear to be a valid file"
I'd be glad if someone could review the code below and help me understand what might be missing here.
Thank you!
//Create list for file URLs - these are files from all different locations
List<String> filenames = new ArrayList<String>();
//..code to add URLs to the list
byte[] buf = new byte[2048];
// Create the ZIP file
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
// Compress the files
for (int i=0; i<filenames.size(); i++) {
FileInputStream fis = new FileInputStream(filenames.get(i).toString());
BufferedInputStream bis = new BufferedInputStream(fis);
// Add ZIP entry to output stream.
File file = new File(filenames.get(i).toString());
String entryname = file.getName();
out.putNextEntry(new ZipEntry(entryname));
int bytesRead;
while ((bytesRead = bis.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
bis.close();
fis.close();
}
ServletOutputStream sos = _response.getOutputStream();
_response.setContentType("application/zip");
_response.setHeader("Content-Disposition", "attachment; filename=\"MyZip.ZIP\"");
sos.write(baos.toByteArray());
out.flush();
out.close();
sos.flush();
Thanks in advance!