这是异步上传到 S3 的 AWS Java 代码示例:
S3AsyncClient client = S3AsyncClient.create();
CompletableFuture<PutObjectResponse> future = client.putObject(
PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(),
AsyncRequestBody.fromFile(Paths.get("myfile.in"))
);
future.whenComplete((resp, err) -> {
try {
if (resp != null) {
System.out.println("my response: " + resp);
} else {
// Handle error
err.printStackTrace();
}
} finally {
// Lets the application shut down. Only close the client when you are completely done with it.
client.close();
}
});
我让它工作了一段时间,但只是好奇为什么你可以在没有凭据的情况下上传到一个存储桶(已阻止所有公共(public)访问打开)?
然后由于某种原因我的访问 key 被删除,我不得不重新生成一个新的,但现在我得到了
software.amazon.awssdk.services.s3.model.S3Exception: The AWS Access Key Id you provided does not exist in our records. (Service: S3, Status Code: 403, Request ID: 2FC0CEEB338D50CB)
。谢谢。
最佳答案
尝试一下,看看它是否适合您:
AwsCredentialsProvider creds = StaticCredentialsProvider.create(AwsBasicCredentials.create("my_access_key", "my_secret_key"));
S3AsyncClient s3Client;
try {
s3Client = S3AsyncClient.builder().credentialsProvider(creds)
.region(Region.US_WEST_1)
.endpointOverride(new URI("https://abc.xyz.com:9021"))
.build();
CompletableFuture<PutObjectResponse> futureGet = s3Client.putObject(
PutObjectRequest.builder()
.bucket("my_bucket_name")
.key("/somepath/anotherpath/myData.pdf")
.build(),
AsyncRequestBody.fromFile(Paths.get("myfile.in")));
futureGet.get();
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
关于java - 上传时如何向 S3AsyncClient 添加凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59735104/