0

I am storing the zip file in to the MSSQL database (varbinary(MAX)) and I have to download the same zip file by reading the contents from database column. My zip file having folders with subfolders and files like below structure

enter image description here

I am trying to create the zip file like below using ByteArrayOutputStream but Its creating the zip file with corrupted data

public ResponseEntity<byte[]> downloadZipFile()
            throws IOException {
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        
            ZipEntry zipEntry = new ZipEntry("SampleZipFile");
            try {
                zipOut.putNextEntry(zipEntry);
                if (zipService.getContent() != null) {
                    zipOut.write(zipService.getContent());
                    zipOut.closeEntry();
                }
            } catch (IOException e) {
                logger.info(e.getMessage());
            }

            byte[] bytes = fos.toByteArray();
            fos.close();
            headers.add(HttpHeaders.CONTENT_TYPE, "application/zip");
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK); 
    }

Any lead/help would be highly appriciated. Thanks in advance!

Amit Jadhav
  • 83
  • 1
  • 9
  • 1
    You have to call `close()` on `zipOut`, not on the `ByteArrayOutputStream`. And you have to do it *before* calling `toByteArray()`. Closing a `ByteArrayOutputStream` has no effect. Mind the existence of [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) – Holger Sep 14 '21 at 06:34

0 Answers0