amazon-s3 - 为什么在 AWS Java SDK 中上传 Multipart 文件比简单的 putObject 调用花费更多时间
问题描述
我正在尝试将文件上传到亚马逊 S3 存储桶当我使用简单的 putobject 调用时,上传文件需要几秒钟我再次尝试使用分段上传机制来减少上传时间,但仍然需要相同甚至更多的时间来上传文件。
使用 AWS 的依赖项:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.909</version>
下面是代码:
private void multi(File file, String keyName){
try {
createInstance();
// Create a list of ETag objects. You retrieve ETags for each object part uploaded,
// then, after each individual part has been uploaded, pass the list of ETags to
// the request to complete the upload.
List<PartETag> partETags = new ArrayList<PartETag>();
// Initiate the multipart upload.
InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketNamedev, keyName);
InitiateMultipartUploadResult initResponse = amazonS3Client.initiateMultipartUpload(initRequest);
// Upload the file parts.
long filePosition = 0;
long contentLength = file.length();
long partSize = 5 * 1024 * 1024; // Set part size to 5 MB.
for (int i = 1; filePosition < contentLength ; i++) {
// Because the last part could be less than 5 MB, adjust the part size as needed.
partSize = Math.min(partSize, (contentLength - filePosition));
// Create the request to upload a part.
UploadPartRequest uploadRequest = new UploadPartRequest()
.withBucketName(bucketNamedev)
.withKey(keyName)
.withUploadId(initResponse.getUploadId())
.withPartNumber(i)
.withFileOffset(filePosition)
.withFile(file)
.withPartSize(partSize);
// Upload the part and add the response's ETag to our list.
UploadPartResult uploadResult = amazonS3Client.uploadPart(uploadRequest);
partETags.add(uploadResult.getPartETag());
filePosition += partSize;
}
// Complete the multipart upload.
CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucketNamedev, keyName,
initResponse.getUploadId(), partETags);
amazonS3Client.completeMultipartUpload(compRequest);
amazonS3Client.shutdown();
System.out.println("Finish..");
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
解决方案
推荐阅读
- python - 如何在已经本地安装 Python (3.7.3) 的 MacBook 上使用 Homebrew 运行我的 Python (3.7.5) 版本
- amazon-web-services - 如何使用 boto3 更改 AWS Glue 爬虫创建的表的名称
- f# - F# 如何从 AND 运算返回布尔值?
- javascript - 如何在css的内联块中显示垂直溢出的项目
- flutter - 防止触摸事件到达父小部件
- json - 使用 arm 模板部署存储帐户时遇到问题
- php - 将值传递到 ACF 前端表单字段
- clickhouse - 如何获得低于所选日期的最大值?
- python - 如何在 Django 中只显示表单中的一个字段
- flutter - 显示错误:内部错误:(java.lang.ClassNotFoundException) com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index