I am trying to implement file upload in a Java web application. When the user uploads a file through the UI, I want it to be stored in amazon amazon s3 storage.
Here is my code for the back-end:
@PostMapping("/upload-file")
public String saveFile(@RequestParam("name") String name, @RequestParam("file")MultipartFile file, RedirectAttributes redirectAttributes){
AWSCredentials credentials = new BasicAWSCredentials("user", "psw");
AmazonS3 s3Client = new AmazonS3Client(credentials);
String bucketName = "kfib";
s3Client.createBucket(bucketName);
s3Client.setRegion(com.amazonaws.regions.Region.getRegion(Regions.EU_WEST_1));
ObjectMetadata md = new ObjectMetadata();
md.setContentType("application/pdf");
// md.set
try{
InputStream inputStream = file.getInputStream();
s3Client.putObject(new PutObjectRequest(bucketName, name, inputStream, md).withCannedAcl(CannedAccessControlList.PublicRead));
S3Object s3Object = s3Client.getObject(new GetObjectRequest(bucketName, name));
log.info("Url of the image:\n");
log.info(s3Object.getObjectContent().getHttpRequest().getURI().toString());
}catch(IOException e){
e.printStackTrace();
}
log.info("upload called with post method...");
return "redirect:/admin/posts";
}
I can upload to files if I upload them to the default region. However, I wish to store my files on another server. I have a bucket in an EU region, if I try to upload something there with the above code, I get the following error code:
com.amazonaws.services.s3.model.AmazonS3Exception: The authorization header is malformed; the region 'us-east-1' is wrong; expecting 'eu-central-1' (Service: Amazon S3; Status Code: 400; Error Code: AuthorizationHeaderMalformed; Request ID: 8EF630B5F0224C4F)
It seems this line
s3Client.setRegion(com.amazonaws.regions.Region.getRegion(Regions.EU_WEST_1));
doesn't have any effect. What am I doing wrong?
I was facing the same issue, but the following worked for me-
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
For Global bucket access
you can set withForceGlobalBucketAccessEnabled
flag to true
like
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withForceGlobalBucketAccessEnabled(true)
.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With