Reputation: 83
Here is the code that I'm using to create a zip file:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
try {
for(int i=0; i<docId.length; i++){
BoxDotComDocumentManager docman = new BoxDotComDocumentManager();
Document d = docman.get(docId[i]);
ZipEntry entry = new ZipEntry(d.getFileName());
entry.setSize(d.getFileBytes().length);
out.putNextEntry(entry);
out.write(d.getFileBytes());
resp.setContentType("application/zip");
resp.setHeader("Content-Disposition", "attachment; filename="+ "zipdemo.zip");
out.closeEntry();
}
} catch (Exception e) {
System.out.println("E = " + e);
}
try {
resp.getOutputStream().write(baos.toByteArray());
resp.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
finally {
baos.close();
out.close();
}
the zip file is being returned to the browser to be downloaded but when I attempt to download the file I'm receiving an error stating that the file cannot be downloaded because the zip file is invalid.
Document is an object which contains all of the information about a file including the actual file.
Any ideas as to what I'm doing wrong? I've tried a lot of permutations of this and none of them seem to work. Thank you in advance.
Keith
Upvotes: 0
Views: 2358
Reputation: 23
Try using the out.write method with 3 arguments.
Replace:
out.write(d.getFileBytes());
With:
out.write(d.getFileBytes(),0,d.getFileBytes().length);
Note: According to the java doc the write method with one parameter doesn't get read.
Writes b.length bytes to this output stream.
The write method of FilterOutputStream calls its write method of three arguments with the arguments b, 0, and b.length.
Note that this method does not call the one-argument write method of its underlying stream with the single argument b.
Making this change in my own code fixed my problem.
Upvotes: 2