当前位置:   article > 正文

Java AWS S3 文件上传实现_aws-java-sdk-s3

aws-java-sdk-s3

一、介绍

Amazon S3(Simple Storage Service)是亚马逊云计算平台提供的一种对象存储服务,可以用于存储和检索任意类型的数据。在Java开发中,我们可以通过AWS SDK for Java来实现与Amazon S3的集成。

官方文档

https://docs.aws.amazon.com/zh_cn/sdk-for-java/v1/developer-guide/examples-s3.html

二、使用

1. 配置maven依赖

<!--amazon s3-->
 <dependency>
     <groupId>com.amazonaws</groupId>
     <artifactId>aws-java-sdk-s3</artifactId>
     <version>1.11.821</version>
 </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2. 配置yaml文件

aws:
  endpoint: your-endpoint
  accessKey: your-accesskey
  secretKey: your-secretkey
  bucketName: your-bucketname
  • 1
  • 2
  • 3
  • 4
  • 5

3. 注入Bean

@Configuration
public class AwsS3Config {

    @Value("${aws.accessKey}")
    private String accessKey;

    @Value("${aws.secretKey}")
    private String secretKey;

    @Value("${aws.endpoint}")
    private String endpoint;

    @Value("${aws.bucketName}")
    private String bucketName;

    @Bean
    public AmazonS3 getAmazonS3() {

        // 创建连接
        ClientConfiguration config = new ClientConfiguration();

        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(endpoint, Regions.CN_NORTH_1.getName());

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

        AmazonS3 s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
        return s3;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

4. 编写service层

@Slf4j
@Service
public class AwsS3Service {


    @Value("${aws.bucketName}")
    private String bucketName;

    @Autowired
    private AmazonS3 amazonS3;

 	public String upload(MultipartFile multipartFile) {
       if (multipartFile.isEmpty()) {
           throw new RuntimeException("文件为空!");
       }
       try {
           ObjectMetadata objectMetadata = new ObjectMetadata();
           objectMetadata.setContentType(multipartFile.getContentType());
           objectMetadata.setContentLength(multipartFile.getSize());
           // 文件后缀
//            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
           String key = UUID.randomUUID().toString();
           // 桶不在则创建桶
           if (!amazonS3.doesBucketExistV2(bucketName)) {
               amazonS3.createBucket(bucketName);
           }
           PutObjectResult putObjectResult = amazonS3.putObject(new PutObjectRequest(bucketName, key, multipartFile.getInputStream(), objectMetadata));
           // 上传成功
           if (null != putObjectResult) {
               GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
               URL url = amazonS3.generatePresignedUrl(urlRequest);
               // 返回url
               return url.toString();
           }
       } catch (Exception e) {
           log.error("Upload files to the bucket,Failed:{}", e.getMessage());
           e.printStackTrace();
       }
       return null;
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

5. 编写controller层

@RestController
@RequestMapping("file")
@Api(tags = "文件上传")
public class FileController {

    @Autowired
    private AwsS3Service awsS3Service;

    @PostMapping("upload")
    @ApiOperation("文件上传接口")
    public APIResponse<String> abilityPictureUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
    
        String url = awsS3Service.upload(file);
        if (StringUtils.isNotEmpty(url)) {
            return APIResponse.success(url);
        }
        return APIResponse.fail("文件上传失败");
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

6. 测试运行结果

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/285842
推荐阅读
相关标签
  

闽ICP备14008679号