spring-cloud-oss存储操以及签名直传和原生sdk中转到oss

前言:分布式服务,一般单独建一个服务器储存文件,可以用阿里云oss服务

和数据直传到OSS相比,以以下方法存在以下缺点:

上传慢:用户数据需先上传到应用服务器,之后再上传到OSS,网络传输时间比直传到OSS多一倍。如果用户数据不通过应用服务器中转,而是直传到OSS,速度将大大提升。而且OSS采用BGP带宽,能保证各地各运营商之间的传输速度。
扩展性差:如果后续用户数量逐渐增加,则应用服务器会成为瓶颈。
费用高:需要准备多台应用服务器。由于OSS上行流量是免费的,如果数据直传到OSS,将节省多台应用服务器的费用。

一、用户在浏览器或App端上传文件到应用服务器,应用服务器再把文件上传到OSS

1.配置参数

1.打开网址:https://oss.console.aliyun.com/overview

spring-cloud-oss存储操以及签名直传和原生sdk中转到oss_第1张图片

2.完成bucket后,设置access key

spring-cloud-oss存储操以及签名直传和原生sdk中转到oss_第2张图片
2种都可以看你需求,我选择第一种<继续使用accesskey>
spring-cloud-oss存储操以及签名直传和原生sdk中转到oss_第3张图片
spring-cloud-oss存储操以及签名直传和原生sdk中转到oss_第4张图片
生成的2个码记住,不要忘了,找个文本存储起来,对接api用
spring-cloud-oss存储操以及签名直传和原生sdk中转到oss_第5张图片

2. 阿里云sdk原生方式建模块

1. idea中新建模块,引入依赖

<dependency>
    <groupId>com.aliyun.ossgroupId>
    <artifactId>aliyun-sdk-ossartifactId>
    <version>3.10.2version>
dependency>

2. 引入yml文件

aliyun:
  oss:
    file:
      endpoint: 你的endpoint
      accessKeyId: 你的accesskeyid
      accessKeySecret: 你的accesskeysecret
      bucketName: 你的文件bucket名字

3. 自定义工具类

//spring初始化执行代码
@Component
public class ConstantPropertiesUtils implements InitializingBean {


    @Value("${aliyun.oss.file.endpoint}")
    private String endPoint;

    @Value("${aliyun.oss.file.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.file.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.file.bucketName}")
    private String bucketName;

    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;


    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endPoint;
        ACCESS_KEY_ID = accessKeyId;
        ACCESS_KEY_SECRET = accessKeySecret;
        BUCKET_NAME = bucketName;
    }
}

4. 引入api接口代码

public static  String uploadFile(MultipartFile file){
        String url =  "";
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        // 填写Bucket名称,例如examplebucket。
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf('.'));
        String fileMainName = UUID.randomUUID().toString().replace("-", "");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String folderFileName = simpleDateFormat.format(new Date());
        String objectName = folderFileName + "/" + fileMainName + suffixName;

//        String objectName = "exampledir/exampleobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
//            https://mrchen-online-education.oss-cn-shanghai.aliyuncs.com/2022-04-29/c3065ff78e804a04b5ef0ede7013c5f5.jpg
//            https://mrchen-online-education.oss-cn-shanghai.aliyuncs.com/2022-04-29/dc16ee33b5b74f8a9a413db20c66933c.jpg
            String downloadUrl = "https://"+bucketName + "." + endpoint + "/" + objectName;
            url = downloadUrl;
            return  url;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            return  url;
        } catch (IOException e) {
            e.printStackTrace();
            return  url;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

3. spring cloud 整合 oss

1. 官方文档:

https://spring-cloud-alibaba-group.github.io/github-pages/2021/en-us/index.html#_spring_cloud_alibaba_cloud_oss

2. 引入依赖

<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alicloud-ossartifactId>
dependency>

3. yml

spring.cloud.alicloud.access-key=Your Alibaba Cloud AK
spring.cloud.alicloud.secret-key=Your Alibaba Cloud SK
spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com

4. 测试

@SpringBootApplication
public class OssApplication {

    @Autowired
    private OSS ossClient;

    @RequestMapping("/")
    public String home() {
        ossClient.putObject("bucketName", "fileName", new FileInputStream("/your/local/file/path"));
        return "upload success";
    }

    public static void main(String[] args) throws URISyntaxException {
        SpringApplication.run(OssApplication.class, args);
    }

}

二、通过签名直传到oss

文档:

https://help.aliyun.com/document_detail/112718.html

返回的 map中带了签名

@RestController
public class OssController {

    @Autowired
    private OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @Value("${spring.cloud.alicloud.secret-key}")
    private String accessKey;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    /**
     * oss签名
     * @return
     */
    @RequestMapping("/oss/policy")
    public  Map ploicy(){

        //https://gulimall-merchen.oss-cn-shanghai.aliyuncs.com/exampledir/exampleobject1.jpg

        // 填写Bucket名称,例如examplebucket。
        // 填写Host地址,格式为https://bucketname.endpoint。
        String host = "https://"+bucket+"."+endpoint;
//        String host = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com";
        // 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
//        String callbackUrl = "https://192.168.0.0:8888";
        // 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format+"/";

        ossClient = new OSSClient(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));
            return respMap;
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
            return null;
        }

    }
}

你可能感兴趣的:(阿里云api以及sdk,springcloud,java,spring,阿里云)