配置阿里云实现文件云存储

【笔记于学习尚硅谷课程所作】

2.1文件云存储

在这里插入图片描述

云存储上传示意图:服务端签名后直传

在这里插入图片描述

(1)配置阿里云

本项目采用阿里云云存储,首先注册

1.登陆阿里云

2.找到对象存储OSS,开通服务,进入控制台
在这里插入图片描述

3.创建Bucket

在这里插入图片描述

4.开通AccessKey–>选择开通子用户的

在这里插入图片描述

5.添加读写权限

在这里插入图片描述

6.在基础设置里设置跨域访问

在这里插入图片描述

(2)建立第三方服务项目

0.对项目进行基本配置

1.引入依赖(common也要引入)

        <!--对象云存储的jar-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

2.配置项目yml

    alicloud:
      access-key: LTAI4G93uUebfuH6ccWcwY3H
      secret-key: KvlZ7v6J68Txex04kTdGF2SS2WGvtJ
      oss:
        endpoint: oss-cn-chengdu-internal.aliyuncs.com
        bucket: gulimall-hanhan

3.配置Controller(实现服务端签名后直传)

@RestController
public class OssController {
    @Autowired
    OSS ossClient;

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

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


    @RequestMapping("/oss/policy")
    public R policy() {
		// host的格式为 bucketname.endpoint
        String host = "https://" + bucket + "." + endpoint; 
        // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/"; // 用户上传文件时指定的前缀。

        Map<String, String> respMap = null;
        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);

            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));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return R.ok().put("data", respMap);
    }
}

4.设置网关(网关的配置的参考

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/106447828