在使用AWS S3存储大文件时,可以选择使用分段上传来提高上传效率和稳定性。以下是使用AWS SDK for Java进行分段上传的示例代码:
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, objectKey); InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
File file = new File(filePath); long contentLength = file.length(); long partSize = 5 * 1024 * 1024; // 设置每个部分的大小为5MB int partCount = (int) Math.ceil((double) contentLength / partSize);
List
UploadPartRequest uploadRequest = new UploadPartRequest()
.withBucketName(bucketName)
.withKey(objectKey)
.withUploadId(initResponse.getUploadId())
.withPartNumber(i + 1)
.withPartSize(partLength)
.withInputStream(fis);
UploadPartResult uploadResult = s3Client.uploadPart(uploadRequest);
partETags.add(uploadResult.getPartETag());
fis.close();
}
CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucketName, objectKey, initResponse.getUploadId(), partETags); s3Client.completeMultipartUpload(compRequest);
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey) .withMethod(HttpMethod.GET) .withExpiration(new Date(System.currentTimeMillis() + 604800000)); // 设置URL的有效期为一周 URL url =