Java AWS 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依赖


 <dependency>
     <groupId>com.amazonawsgroupId>
     <artifactId>aws-java-sdk-s3artifactId>
     <version>1.11.821version>
 dependency>

2. 配置yaml文件

aws:
  endpoint: your-endpoint
  accessKey: your-accesskey
  secretKey: your-secretkey
  bucketName: your-bucketname

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

}

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

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("文件上传失败");
    }
}

6. 测试运行结果

Java AWS S3 文件上传实现_第1张图片

你可能感兴趣的:(Java,java,aws,1024程序员节)