1

I take a multipartfile (i.e. SAMPLE.csv) in input. I should zip it (i.e. SAMPLE.zip) and store it via FTP.

public void zipAndStore(MultipartFile file) {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ZipOutputStream zos = new ZipOutputStream(baos);
         InputStream is = file.getInputStream()) {
         ZipEntry zipEntry = new ZipEntry("SAMPLE.zip");
         zos.putNextEntry(zipEntry);
         byte[] bytes = new byte[1024];
         int length;
         while ((length = is.read(bytes)) >= 0) {
              zos.write(bytes, 0, length);
         }
         zos.closeEntry();
         storeFtp("SAMPLE.zip", new ByteArrayInputStream(baos.toByteArray()));
     } catch (Exception e) {
     }
}

The storeFtp use the org.apache.commons.net.ftp.FTPClient.storeFile(String remote, InputStream local) method.

The problem is that the uploaded file is corrupted and i'm unable to manually decompress. What's wrong?

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
user2520969
  • 1,389
  • 6
  • 20
  • 30

1 Answers1

1

A zipfile has a list of DirEntries and a endLocator at the end of the file (after all the ZipFileRecords, i.e. the ZipEntries in the code).

So you probably have to close the zipfile before calling storeFtp() to make sure the DirEntries and the endLocator are written to the file:

zos.closeEntry();
zos.close();
storeFtp("SAMPLE.zip", new ByteArrayInputStream(baos.toByteArray()));

(I don't know Java that well, so I can't check or test the full code)

Also check out this answer.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
  • @user2520969 Looking at the code, I also think you have to name the ZipEntry SAMPLE.csv instead of SAMPLE.zip, since it's the file inside the zipfile. – Danny_ds Apr 18 '20 at 15:55