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

迷南。 2023-02-14 02:09 68阅读 0赞

文章目录

    • 2.1文件云存储
      • (1)配置阿里云
      • (2)建立第三方服务项目

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

2.1文件云存储

在这里插入图片描述

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

在这里插入图片描述

(1)配置阿里云

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

1.登陆阿里云

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

3.创建Bucket

在这里插入图片描述

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

在这里插入图片描述

5.添加读写权限

在这里插入图片描述

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

在这里插入图片描述

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

0.对项目进行基本配置

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

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

2.配置项目yml

  1. alicloud:
  2. access-key: LTAI4G93uUebfuH6ccWcwY3H
  3. secret-key: KvlZ7v6J68Txex04kTdGF2SS2WGvtJ
  4. oss:
  5. endpoint: oss-cn-chengdu-internal.aliyuncs.com
  6. bucket: gulimall-hanhan

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

  1. @RestController
  2. public class OssController {
  3. @Autowired
  4. OSS ossClient;
  5. @Value("${spring.cloud.alicloud.oss.endpoint}")
  6. private String endpoint;
  7. @Value("${spring.cloud.alicloud.oss.bucket}")
  8. private String bucket;
  9. @Value("${spring.cloud.alicloud.access-key}")
  10. private String accessId;
  11. @RequestMapping("/oss/policy")
  12. public R policy() {
  13. // host的格式为 bucketname.endpoint
  14. String host = "https://" + bucket + "." + endpoint;
  15. // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
  16. String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  17. String dir = format + "/"; // 用户上传文件时指定的前缀。
  18. Map<String, String> respMap = null;
  19. try {
  20. long expireTime = 30;
  21. long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
  22. Date expiration = new Date(expireEndTime);
  23. PolicyConditions policyConds = new PolicyConditions();
  24. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
  25. policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
  26. String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
  27. byte[] binaryData = postPolicy.getBytes("utf-8");
  28. String encodedPolicy = BinaryUtil.toBase64String(binaryData);
  29. String postSignature = ossClient.calculatePostSignature(postPolicy);
  30. respMap = new LinkedHashMap<String, String>();
  31. respMap.put("accessid", accessId);
  32. respMap.put("policy", encodedPolicy);
  33. respMap.put("signature", postSignature);
  34. respMap.put("dir", dir);
  35. respMap.put("host", host);
  36. respMap.put("expire", String.valueOf(expireEndTime / 1000));
  37. } catch (Exception e) {
  38. System.out.println(e.getMessage());
  39. }
  40. return R.ok().put("data", respMap);
  41. }
  42. }

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

发表评论

表情:
评论列表 (有 0 条评论,68人围观)

还没有评论,来说两句吧...

相关阅读

    相关 阿里存储OSS

    为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS。 一 开通“对象存储OSS”服务 1 申请阿里云账号 2 实名认证 3 开