Umer Hayat
Umer Hayat

Reputation: 2001

zipping binary data in java

I am trying to zip a group of binary data (result set returned from database) into a single file. Which can be downloaded via web application. Following code is used to zip the result set and write the zip file to HttpServletResponse

String outFilename = "outfile.zip";
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename= " + outFilename);
OutputStream os = response.getOutputStream();
ZipOutputStream out = new ZipOutputStream(os);
for (int i = 0; i < cardFileList.size(); i++) {

    CardFile cardFile = cardFileList.get(i);
    out.putNextEntry(new ZipEntry(cardFile.getBinaryFileName()));
    out.write(cardFile.getBinaryFile(), 0, cardFile.getBinaryFile().length);
    out.closeEntry();
}
// Complete the ZIP file
out.flush();
out.close();
os.close();

The problem is that while unzipping the downloaded zip file using WinRar I get following error :

File Path: Either multipart or corrupt ZIP archive

Can someone point out where am I making mistake?. Any help would be appreciated.

[EDIT] I tried response.setContentType("application/zip"); but same result.

Upvotes: 4

Views: 2723

Answers (2)

Paul Jowett
Paul Jowett

Reputation: 6581

Your code looks correct for producing the file. So the problem is probably in your downloading.

  1. look at the file you have downloaded. What is it's size?
  2. try a tool other than your WinRar and see what you have. 7Zip is decent.

Upvotes: 0

prunge
prunge

Reputation: 23268

The following code works for me:

FileOutputStream os = new FileOutputStream("out.zip");
ZipOutputStream zos = new ZipOutputStream(os);
try
{
    for (int i = 1; i <= 5; i++)
    {
        ZipEntry curEntry = new ZipEntry("file" + i + ".txt");
        zos.putNextEntry(curEntry);
        zos.write(("Good morning " + i).getBytes("UTF-8"));
    }
}
finally
{
    zos.close();
}

Zip files generated with this code opens up with 7-zip without problem.

  • Check that the response from the servlet is not actually a 404 or 500 error page. Pick a small response and open it up with a hex editor or even a text editor. Zip files start with a 'PK' magic number which should be visible even in a text editor.
  • Try saving to file instead of servlet output stream for starters and see if that makes a difference.
  • Could there be a filter modifying your servlet's output / corrupting the ZIP?

Upvotes: 2

Related Questions