So I'm grabbing a collection of blobs from a database (various mimetypes) and trying to zip them up to be downloaded by users through an http response. I can get the download to happen, but when I try to open the downloaded zip file it says "The archive is either in unknown format or damaged." I've tried the following code with application/zip, application/octet-stream, and application/x-zip-compressed, but I'm starting to assume that the issue is in how I'm adding the files. I'm also using Java 7 and Grails 2.2.4.
Any help with this would be greatly appreciated. Thanks!
final ZipOutputStream out = new ZipOutputStream(new FileOutputStream("test.zip"));
for (Long id : ids){
Object[] stream = inlineSamplesDataProvider.getAttachmentStream(id);
if (stream) {
String fileName = stream[0]
String mimeType = (String) stream[1];
InputStream inputStream = stream[2]
byte[] byteStream = inputStream.getBytes();
ZipEntry zipEntry = new ZipEntry(fileName)
out.putNextEntry(zipEntry);
out.write(byteStream, 0, byteStream.length);
out.closeEntry();
}
}
out.close();
response.setHeader("Content-Disposition", "attachment; filename=\"" + "test.zip" + "\"");
response.setHeader("Content-Type", "application/zip");
response.outputStream << out;
response.outputstream.flush();
I found the answer here: Returning ZipOutputStream to browser
All right, so what ended up working for me was converting the ZipOutputStream to a ByteArrayOutputStream and writing it to a response as a byte[]:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ZipOutputStream out = new ZipOutputStream(baos);
Calendar cal = Calendar.getInstance();
String date = new SimpleDateFormat("MMM-dd").format(cal.getTime());
final String zipName = "COA_Images-" + date + ".zip";
for (Long id: ids) {
Object[] stream = inlineSamplesDataProvider.getAttachmentStream(id);
if (stream) {
String fileName = stream[0];
String mimeType = (String) stream[1];
InputStream inputStream = stream[2];
byte[] byteStream = inputStream.getBytes();
ZipEntry zipEntry = new ZipEntry(fileName)
out.putNextEntry(zipEntry);
out.write(byteStream, 0, byteStream.length);
out.closeEntry();
}
}
out.close();
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + "\"");
response.setHeader("Content-Type", "application/zip");
response.getOutputStream().write(baos.toByteArray());
response.flushBuffer();
baos.close();
Thanks to everyone who helped!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With