Need to upload a large file to AWS S3 using multipart-upload using stream instead of using /tmp of lambda.The file is uploaded but not uploading completely.
In my case the size of each file in zip cannot be predicted, may be a file goes up to 1 Gib of size.So I used ZipInputStream to read from S3 and I want to upload it back to S3.Since I am working on lambda, I cannot save the file in /tmp of lambda due to the large file size.So I tried to read and upload directly to S3 without saving in /tmp using S3-multipart upload. But I faced an issue that the file is not writing completely.I suspect that the file is overwritten every time. Please review my code and help.
public void zipAndUpload {
byte[] buffer = new byte[1024];
try{
File folder = new File(outputFolder);
if(!folder.exists()){
folder.mkdir();
}
AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient();
S3Object object = s3Client.getObject("mybucket.s3.com","MyFilePath/MyZip.zip");
TransferManager tm = TransferManagerBuilder.standard()
.withS3Client(s3Client)
.build();
ZipInputStream zis =
new ZipInputStream(object.getObjectContent());
ZipEntry ze = zis.getNextEntry();
while(ze!=null){
String fileName = ze.getName();
System.out.println("ZE " + ze + " : " + fileName);
File newFile = new File(outputFolder + File.separator + fileName);
if (ze.isDirectory()) {
System.out.println("DIRECTORY" + newFile.mkdirs());
}
else {
filePaths.add(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(len);
InputStream targetStream = new ByteArrayInputStream(buffer);
PutObjectRequest request = new PutObjectRequest("mybucket.s3.com", fileName, targetStream ,meta);
request.setGeneralProgressListener(new ProgressListener() {
public void progressChanged(ProgressEvent progressEvent) {
System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
}
});
Upload upload = tm.upload(request);
}
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}