亚马逊S3上传下载文件

1创建连接

@Data
@ConfigurationProperties(prefix = "amazon.s3")
public class AmazonS3Properties {

    /**
     * bucket名称
     */
    private String bucketName;

    /**
     * 终端
     */
    private String endpoint;

    /**
     * 访问密钥
     */
    private String accessKey;

    /**
     * 秘密密钥
     */
    private String secretKey;

}
@Configuration
@EnableConfigurationProperties(AmazonS3Properties.class)
public class AmazonS3AutoConfiguration {
 
    private AmazonS3Properties amazonS3Properties;
 
    @Autowired
    public void setAmazonS3Properties(AmazonS3Properties amazonS3Properties) {       
        this.amazonS3Properties = amazonS3Properties;
    }
 
    @Bean
    public AmazonS3 amazonS3() {       
        // 初始化 BasicAWSCredentials
        BasicAWSCredentials credentials =
                       new BasicAWSCredentials(amazonS3Properties.getAccessKey(), amazonS3Properties.getSecretKey());
 
        // 初始化 configuration, set protocol is HTTP
        ClientConfiguration configuration = new ClientConfiguration();
        configuration.setProtocol(Protocol.HTTP);
        configuration.setSignerOverride("S3SignerType");
 
        // 初始化 endpoint configuration
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(
                        "http://" + amazonS3Properties.getEndpoint(), Regions.CN_NORTH_1.getName());
        // 创建AmazonS3
        return AmazonS3ClientBuilder.standard().withClientConfiguration(configuration)
                        .withEndpointConfiguration(endpointConfiguration)
                        .withPathStyleAccessEnabled(true)
                        .withCredentials(new AWSStaticCredentialsProvider(credentials)).build();
    }
}
@Slf4j
@Component
public class S3FileServiceImpl implements S3FileService {

    /**
     * 下载文件数据byte大小
     */
    private static final int BYTESIZE = 10240;
    /**
     * 桶名
     */
    private String bucketName;
    /**
     * amazon s3
     */
    private final AmazonS3 amazonS3;
    public S3FileServiceImpl(AmazonS3 amazonS3, AmazonS3Properties amazonS3Properties) {
        this.amazonS3 = amazonS3;
        this.bucketName = amazonS3Properties.getBucketName();
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return {@link FileDto}
     */
    @Override
    public void uploadFile(MultipartFile file) {
        try {
            if (null == file || file.getSize() <= 0) {
                throw new SystemException("文件为空");
            }
            String fileName = file.getOriginalFilename();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(file.getContentType());
            objectMetadata.setContentLength(file.getSize());
            objectMetadata.setContentEncoding(StaticParam.CHARSET_UTF8);
            String uuidFileName =
                  StringUtil.getRandomUUIDStr();
            PutObjectRequest request =
                    new PutObjectRequest(bucketName, uuidFileName, file.getInputStream(), objectMetadata);
            amazonS3.putObject(request);
             //得到预览的url
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                    bucketName, fileName).withMethod(HttpMethod.GET)
                    .withExpiration(expiration);
            URL fileUrl = amazonS3
                    .generatePresignedUrl(generatePresignedUrlRequest);
        } catch (Exception e) {
            log.error("上传异常", e);
            throw new SystemException(e.getMessage());
        }
    }

    /**
     * 下载文件
     *
     * @param key 键
     * @param res response
     */
    @Override
    public void downLoadFile(String key, ServletResponse res) {
        S3Object object = amazonS3.getObject(new GetObjectRequest(bucketName, key));
        log.info("ETag: [{}]",object.getObjectMetadata().getETag());
        InputStream inputStream = object.getObjectContent();
        try (OutputStream outputStream = res.getOutputStream();
             BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            // 发送给客户端的数据
            byte[] buf = new byte[BYTESIZE];
            int len;
            while ((len = bis.read(buf, 0, buf.length)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            log.error("下载文件异常", e);
            throw new SystemException("下载文件异常!");
        }

    }

    /**
     * 预览文件 提供可以访问的url
     *
     * @param key 关键
     * @return {@link org.springframework.core.io.Resource}
     */
    @Override
    public org.springframework.core.io.Resource getFile(String key) {
        if(key==null){
            throw new SystemException("文件不存在");
        }
        S3Object object = amazonS3.getObject(new GetObjectRequest(bucketName, key));
        InputStream inputStream = object.getObjectContent();
        return new InputStreamResource(inputStream);
    }

    /**
     * s3 删除文件
     *
     * @param fileDto 文件dto
     */
    @Override
    public void delS3File(FileDto fileDto) {
        if (fileDto != null && StringUtil.isNotBlank(fileDto.getS3Key())) {
            try {
                amazonS3.deleteObject(bucketName, fileDto.getS3Key());
            } catch (SdkClientException e) {
                log.error("删除文件异常!", e);
                throw new SystemException("删除文件异常!");
            }
        }else{
            throw new SystemException("删除文件异常!文件不存在或路径不存在");
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值