I was trying to upload a file to s3 bucket but getting an " Access Denied" error. So checking using aws cli - It was found that we need to pass SSE kms key id to make it work
Bucket policy added with conditions: s3:x-amz-server-side-encryption: aws:kms and s3:x-amz-server-side-encryption-aws-kms-key-id: key-id. Below is my code which is still giving Access error.
Can someone please help?
public class FileUploadToAWSS3 {
private static final String SUFFIX = "/";
private static final String kms_cmk_id = "arn:aws:kms:";
public void uploadFileToS3Bucket(MultipartFile multipartFile) throws IOException {
AWSCredentials credentials = new BasicAWSCredentials(
"access_key",
"secret_key");
AmazonS3 s3client = new AmazonS3Client(credentials);
s3client.setEndpoint("https://s3.eu-west-1.amazonaws.com");
String bucketName = "my-bucket";
s3client.createBucket(bucketName);
String quarter1 = "root/Folder1";
createFolder(bucketName, quarter1, s3client);
String fileName = quarter1 + SUFFIX + multipartFile.getOriginalFilename();
ObjectMetadata omd = new ObjectMetadata();
omd.setContentType(multipartFile.getContentType());
omd.setContentLength(multipartFile.getSize());
omd.setHeader("filename", multipartFile.getOriginalFilename());
s3client.putObject(new PutObjectRequest(bucketName, fileName,multipartFile.getInputStream(), omd)
.withCannedAcl(CannedAccessControlList.Private)
.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(kms_cmk_id)));
}
private void createFolder(String bucketName, String folderName, AmazonS3 client) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(0);
InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
folderName + SUFFIX, emptyContent, metadata);
client.putObject(putObjectRequest);
}
}
Just to update as how it was resolved:-
Since a service instance (provisioned via cloud foundry) of S3 bucket was used; so bucket was created and specific create bucket command was not required.
Removed the code s3client.createBucket(bucketName);
and it worked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.