S3 Demo

package com.xinyan.mp.quality.manager;

import cn.hutool.core.util.StrUtil;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 
 * @date 2019/10/28 9:55
 * @Description 文件上传
 */
@Slf4j
@Component
public class FileManager {
    /**
     * 首先需要保证s3上已经存在该存储桶,且同名必须大写开头
     */
    @Value("${aws.bucket}")
    private String awsBucket;

    /**
     * AWS 访问密钥
     */
    @Value("${aws.accessKey}")
    private String accessKey;

    /**
     * AWS SECRET_KEY
     */
    @Value("${aws.secretKey}")
    private String secretKey;

    /**
     * AWS 云平台地址
     */
    @Value("${aws.url}")
    private String url;

    private AmazonS3 amazonS3Client;

    @PostConstruct
    public void init() {
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTP);
        amazonS3Client = AmazonS3ClientBuilder.standard().withCredentials(
                new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))).
                withClientConfiguration(clientConfig).
                withEndpointConfiguration(
                        new AwsClientBuilder.EndpointConfiguration(url, Regions.DEFAULT_REGION.getName())).
                build();
        /*枚举bucket下对象*/
       /* ObjectListing objects = amazonS3Client.listObjects(awsBucket);
        do {
            for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                log.info(objectSummary.getKey());
            }
            objects = amazonS3Client.listNextBatchOfObjects(objects);
        } while (objects.isTruncated());*/
    }

    /**
     * 上传
     *
     * @param file
     * @param fileName
     * @return
     * @throws FileNotFoundException
     */
    public String upload(File file, String fileName) throws FileNotFoundException {
        String fileDirName = awsBucket + "/xxxxx/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //存入文件
        amazonS3Client.putObject(fileDirName, fileName, new FileInputStream(file), new ObjectMetadata());
        //修改对象的ACL访问权限为公有
        amazonS3Client.setObjectAcl(fileDirName, fileName, CannedAccessControlList.PublicReadWrite);
        boolean delete = file.delete();
        log.info("删除临时文件:【{}】 状态:{},", file.getAbsolutePath(), delete);
        return amazonS3Client.getUrl(fileDirName, fileName).toString();
    }

    /**
     * 刪除
     *
     * @param path
     */
    public void delete(String path) {
        String str = path.substring(path.indexOf(awsBucket));
        String bucketName = StrUtil.sub(str, 0, str.lastIndexOf("/"));
        String key = StrUtil.sub(str, str.lastIndexOf("/") + 1, str.length());
        amazonS3Client.deleteObject(bucketName, key);
    }

    /**
     * 下载文件
     *
     * @param path
     */
    public InputStream download(String path) {
        String str = path.substring(path.indexOf(awsBucket));
        String bucketName = StrUtil.sub(str, 0, str.lastIndexOf("/"));
        String key = StrUtil.sub(str, str.lastIndexOf("/") + 1, str.length());
        S3Object s3Object = amazonS3Client.getObject(bucketName, key);
        return s3Object.getObjectContent();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值