Spring 如何为amazonS3客户端设置区域?

Spring 如何为amazonS3客户端设置区域?,spring,amazon-web-services,amazon-s3,cloud,Spring,Amazon Web Services,Amazon S3,Cloud,我试图在JavaWeb应用程序中实现文件上传。当用户通过UI上传文件时,我希望它存储在AmazonS3存储中 以下是我的后端代码: @PostMapping("/upload-file") public String saveFile(@RequestParam("name") String name, @RequestParam("file")MultipartFile file, RedirectAttributes redirectAttributes){ AWSCredenti

我试图在JavaWeb应用程序中实现文件上传。当用户通过UI上传文件时,我希望它存储在AmazonS3存储中

以下是我的后端代码:

@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";
}
如果我将文件上载到默认区域,则可以上载到文件。但是,我希望将文件存储在另一台服务器上。我在欧盟地区有一个bucket,如果我试图用上面的代码上传一些东西,我会得到以下错误代码:

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));

没有任何效果。我做错了什么?

我也面临着同样的问题,但以下几点对我起了作用-


AmazonS3 s3Client=AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1.build()

用于全局存储桶访问

您可以使用ForceGlobalBucketAccessEnabled将
标志设置为true


AmazonS3Client.setRegion()
不推荐使用。您没有尝试使用
AwsClientBuilder.setRegion(字符串)
?考虑到Java的标准繁琐性,我很可能弄错了,但是
s3Client.setRegion(com.amazonaws.regions.Region.getRegion(regions.EU_-WEST_1))似乎有点。。。冗余的这不仅仅是
s3Client.setRegion(Regions.EU_WEST_1)
;抱歉@rpuch我显然花了超过5分钟的时间写我的评论,鉴于你的评论,这本身有些多余。。。你的问题似乎比我的好。我想你在上面的代码中替换了传递给BasicAWSCredentials的AccessKey/SecretKey值以确保安全,而不是真正传递用户名和密码?值得检查它们是否正确,因为在访问密钥或密钥无效时调用AmazonS3Client.headBucket()时,我遇到了这样一个误导性错误。
AmazonS3 s3client = AmazonS3ClientBuilder
            .standard()
            .withCredentials(new AWSStaticCredentialsProvider(credentials))
            .withForceGlobalBucketAccessEnabled(true)
            .build();