Skip to content

Instantly share code, notes, and snippets.

@jrgleason
Created March 15, 2018 14:08
Show Gist options
  • Save jrgleason/0aa993f3651d09f9f0b6e1140a8d1658 to your computer and use it in GitHub Desktop.
Save jrgleason/0aa993f3651d09f9f0b6e1140a8d1658 to your computer and use it in GitHub Desktop.
Example upload multipart s3
public void uploadFile(MultipartFile file) throws IOException{
long contentLength = file.getBytes().length;
long partSize = 5 * 1024 * 1024;
String key = file.getOriginalFilename();
InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(
bucket, key);
InitiateMultipartUploadResult initResponse =
client.initiateMultipartUpload(initRequest);
List<PartETag> partETags = new ArrayList<>();
int partNumber = 1;
for (long filePosition = 0; filePosition < contentLength; filePosition += partSize) {
// Last part can be less than 5 MB. Adjust part size.
partSize = Math.min(partSize, (contentLength - filePosition));
System.out.println(String.format("%d | %d | %d", partSize, filePosition, contentLength));
UploadPartRequest uploadRequest = new UploadPartRequest()
.withBucketName(bucket).withKey(file.getOriginalFilename())
.withUploadId(initResponse.getUploadId()).withPartNumber(partNumber)
.withFileOffset(filePosition)
.withInputStream(file.getInputStream())
.withPartSize(partSize);
PartETag partETag = client.uploadPart(uploadRequest).getPartETag();
// Upload part and add response to our list.
partETags.add(partETag);
partNumber++;
}
CompleteMultipartUploadRequest compRequest = new
CompleteMultipartUploadRequest(
bucket,
file.getOriginalFilename(),
initResponse.getUploadId(),
partETags);
client.completeMultipartUpload(compRequest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment