首先,需要在AWS控制台创建您的访问
密钥
和
密钥
ID。然后,使用以下Java代码获取临时
安全
凭证,以访问S3存储桶并上传文件:
// Set the access key and secret access key
final String ACCESS_KEY = "YOUR_ACCESS_KEY";
final String SECRET_ACCESS_KEY = "YOUR_SECRET_ACCESS_KEY";
// Create a new BasicAWSCredentials object
BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_ACCESS_KEY);
// Set the Amazon S3 bucket name and region
final String BUCKET_NAME = "YOUR_BUCKET_NAME";
final String REGION = "YOUR_BUCKET_REGION";
// Create a new AmazonS3Client object
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(REGION)
.build();
// Create a new session token request
GetSessionTokenRequest sessionRequest = new GetSessionTokenRequest();
// Set the duration for the temporary security credentials
sessionRequest.setDurationSeconds(3600);
// Retrieve the temporary security credentials
GetSessionTokenResult sessionTokenResult = s3client.getSessionToken(sessionRequest);
Credentials sessionCredentials = sessionTokenResult.getCredentials();
// Use the temporary security credentials to access the S3 bucket
AmazonS3 s3clientTemp = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicSessionCredentials(
sessionCredentials.getAccessKeyId(),
sessionCredentials.getSecretAccessKey(),
sessionCredentials.getSessionToken())))
.withRegion(REGION)
.build();
// Upload a file to the S3 bucket
File file = new File("YOUR_FILE_PATH");
String keyName = "YOUR_FILE_NAME";
s3clientTemp.putObject(BUCKET_NAME, keyName, file);
请确保将所有YOUR_文本替换为您自己的访问密钥,密钥ID,存储桶名称,存储桶区域,文件路径和文件名。