Zipping binary data in java

I am trying to pin a group of binary data (a set of results returned from a database) into a single file. What can be downloaded through the web application. The following code is used to zip a result set and write a zip file to an 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 when unpacking the downloaded zip file using WinRar, I get the following error:

File path: personal or damaged ZIP archive

Can someone please indicate where I am making a mistake? Any help would be appreciated.

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

+4
source share
2 answers

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(); } 

Mail files generated using this code open with 7-zip without any problems.

  • Make sure that the servlet’s response is not really a 404 or 500 error page. Select a small answer and open it with a hex editor or even a text editor. Zip files start with the magic number "PK", which should be visible even in a text editor.
  • Try saving to a file instead of the servlet starter output stream and see if this has changed.
  • Could there be a filter modifying your servlet output / zip corruption?
+1
source

Your code looks right to create the file. So the problem is probably in your download.

  • Check out the file you downloaded. What size?
  • try a tool different from your WinRar and see what you have. 7Zip is decent.
0
source

Source: https://habr.com/ru/post/1385279/


All Articles