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?
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.