【发布时间】:2018-08-13 17:04:25
【问题描述】:
我正在尝试将一个大文件上传到使用令牌的服务器,并且令牌在 10 分钟后过期,所以如果我上传一个小文件,它会起作用,因此如果文件大,我会遇到一些问题并且将在访问被拒绝时一直尝试上传
所以我需要刷新 BasicAWSCredentials 中的令牌,而不是用于 AWSStaticCredentialsProvider 因此我不确定我该怎么做,请帮助 =)
值得一提的是,我们使用本地服务器(不是亚马逊云)来提供令牌,并且为了方便我们使用亚马逊的代码。
这是我的代码:
public void uploadMultipart(File file) throws Exception {
//this method will give you a initial token for a given user,
//than calculates when a new token is needed and will refresh it just when necessary
String token = getUsetToken();
String existingBucketName = myTenant.toLowerCase() + ".package.upload";
String endPoint = urlAPI + "s3/buckets/";
String strSize = FileUtils.byteCountToDisplaySize(FileUtils.sizeOf(file));
System.out.println("File size: " + strSize);
AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endPoint, null);//note: Region has to be null
//AWSCredentialsProvider
BasicAWSCredentials sessionCredentials = new BasicAWSCredentials(token, "NOT_USED");//secretKey should be set to NOT_USED
AmazonS3 s3 = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(sessionCredentials))
.withEndpointConfiguration(endpointConfiguration)
.enablePathStyleAccess()
.build();
int maxUploadThreads = 5;
TransferManager tm = TransferManagerBuilder
.standard()
.withS3Client(s3)
.withMultipartUploadThreshold((long) (5 * 1024 * 1024))
.withExecutorFactory(() -> Executors.newFixedThreadPool(maxUploadThreads))
.build();
PutObjectRequest request = new PutObjectRequest(existingBucketName, file.getName(), file);
//request.putCustomRequestHeader("Access-Token", token);
ProgressListener progressListener = progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
request.setGeneralProgressListener(progressListener);
Upload upload = tm.upload(request);
LocalDateTime uploadStartedAt = LocalDateTime.now();
log.info("Starting upload at: " + uploadStartedAt);
try {
upload.waitForCompletion();
//upload.waitForUploadResult();
log.info("Upload completed. " + strSize);
} catch (Exception e) {//AmazonClientException
log.error("Error occurred while uploading file - " + strSize);
e.printStackTrace();
}
}
【问题讨论】:
-
值得一读:thoughtworks.com/mingle/infrastructure/2015/06/15/…。尝试获取更长久的凭据。
-
@jarmod - 谢谢你的回复,很棒的帖子,这可能是一个选择,因此这篇文章大约有 3 年的历史了,我仍然希望使用 aws java sdk 可能有另一种解决方法跨度>
-
@jarmod 找到了解决办法请看一下,谢谢回复
标签: java amazon-web-services amazon-s3 aws-sdk aws-sdk-java-2.0