Hi All,
I am trying to create a zip file on the fly and write it to a javax.servlet.ServletResponse object. Writing the zip file to a FileOutputStream works fine but writing to response.getOutputStream() is not working -- I get "corrupt or invalid zip file" error.
For some reason some extra bytes are being written to response.getOutputStream() and thus causing Window's zip utility to think that my file is corrupt. However, other zip utilities (like winzip, extractnow, linux's unzip command etc) can unzip my file -- they only give me a warning message that my zipped filesize is invalid.
Any suggestions ? Please help!
My zip function:
public void zipReports(javax.servlet.ServletResponse response, String generationid) {
String query = "SELECT * FROM stg_report WHERE generationid='" + generationid + "'";
try {
java.util.zip.ZipOutputStream zipOutputStream = new java.util.zip.ZipOutputStream(response.getOutputStream());
java.util.zip.ZipOutputStream zipFOS = new java.util.zip.ZipOutputStream(new java.io.FileOutputStream("/home/rorokimdim/try.zip"));
stmt = myConn.createStatement();
myRS = stmt.executeQuery(query);
while (myRS.next()) {
java.sql.Blob blob = myRS.getBlob("pdfformat");
byte[] buf = new byte[1024];
long genid = myRS.getLong("genid");
String entryName = generationid + "_" + genid + ".pdf";
java.io.InputStream inputStream = blob.getBinaryStream();
java.util.zip.ZipEntry entry = new java.util.zip.ZipEntry(entryName);
//zipOutputStream.setLevel(java.util.zip.Deflater.DEFAULT_COMPRESSION);
//zipOutputStream.setMethod(java.util.zip.ZipOutputStream.STORED);
zipOutputStream.putNextEntry(entry);
zipFOS.putNextEntry(entry);
//java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
int len = 0;
int size=0;
while ((len = inputStream.read(buf)) > 0) {
zipOutputStream.write(buf, 0, len);
zipFOS.write(buf, 0, len);
//crc32.update(buf,0,len);
size += len;
}
entry.setSize(size);
//entry.setCrc(crc32.getValue());
zipOutputStream.closeEntry();
zipFOS.closeEntry();
inputStream.close();
}
zipOutputStream.flush();
zipOutputStream.close();
zipFOS.close();
}
catch (Exception e) {
System.out.println("\n\nMy error:\n" + e.toString() + "\nerror ends");
}
finally {
try {
if (myRS != null) myRS.close();
if (myConn != null) myConn.close();
if (stmt != null) stmt.close();
}
catch (Exception e) {
}
}
}
My jsp file:
response.setContentType("application/zip");
response.setHeader("Content-disposition","attachment; filename=multiples.zip");
Zipper.zipReports(response,genID);