我正在尝试在Java Web应用程序中实现文件上载。当用户通过用户界面上传文件时,我希望将其存储在亚马逊亚马逊s3存储中。
以下是我的后端代码:
@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";
}
如果我将它们上传到默认区域,我可以上传到文件。但是,我希望将我的文件存储在另一台服务器上。我在欧盟地区有一个存储桶,如果我尝试使用上面的代码上传某些内容,我会收到以下错误代码:
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)
看来这一行
s3Client.setRegion(com.amazonaws.regions.Region.getRegion(Regions.EU_WEST_1));
没有任何影响。我做错了什么?
答案 0 :(得分:4)
我遇到了同样的问题,但以下情况对我有用 -
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()。withRegion(Regions.US_EAST_1).build();
答案 1 :(得分:2)
用于全局存储段访问
您可以将withForceGlobalBucketAccessEnabled
标志设置为true
喜欢
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withForceGlobalBucketAccessEnabled(true)
.build();