Created
March 15, 2018 14:08
-
-
Save jrgleason/0aa993f3651d09f9f0b6e1140a8d1658 to your computer and use it in GitHub Desktop.
Example upload multipart s3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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