当前位置:   article > 正文

阿里云对象存储(oss)之服务端签名后直传_阿里云oss 后端直接上传文件 unlimitedqrcode

阿里云oss 后端直接上传文件 unlimitedqrcode

本文主要介绍如何基于Post Policy的使用规则在服务端通过各种语言代码完成签名,然后通过表单直传数据到OSS。由于服务端签名直传无需将AccessKey暴露在前端页面,相比JavaScript客户端签名直传具有更高的安全性。

 原理流程如图所示:

开通阿里云oss步骤:

第一步注册登录阿里云

第二步搜索对象存储oss并开通进入OSS管理控制台

第三步创建bucket仓库(需要阿里云官方验证要一定时间 具体创建细节自行百度即可)

第四步修改CORS(否则上传图片会有跨域问题)

第五步开通自己的AccessKey 会有accesskey id 和 accesskey secret 给你,至于往后在此拿accesskey secret则需要短信验证了 

后端步骤

第一步引入 依赖

  1. <!--对象存储-->
  2. <dependency>
  3. <groupId>com.alibaba.cloud</groupId>
  4. <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
  5. </dependency>
  6. <!--com.alibaba.cloud依赖管理-->
  7. <dependencyManagement>
  8. <dependencies>
  9. <dependency>
  10. <groupId>com.alibaba.cloud</groupId>
  11. <artifactId>spring-cloud-alibaba-dependencies</artifactId>
  12. <version>2.1.0.RELEASE</version>
  13. <type>pom</type>
  14. <scope>import</scope>
  15. </dependency>
  16. </dependencies>
  17. </dependencyManagement>

第二步配置核心配置文件  

application.yml  

 application.properties   (开启服务配置功能  可配可不配)

 java代码:

  1. package com.gulimall.gulimallthirdparty.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.aliyun.oss.OSS;
  4. import com.aliyun.oss.OSSClient;
  5. import com.aliyun.oss.common.utils.BinaryUtil;
  6. import com.aliyun.oss.model.MatchMode;
  7. import com.aliyun.oss.model.PolicyConditions;
  8. import com.atguigu.common.utils.R;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import java.io.UnsupportedEncodingException;
  14. import java.security.KeyStore;
  15. import java.text.SimpleDateFormat;
  16. import java.util.Date;
  17. import java.util.LinkedHashMap;
  18. import java.util.Map;
  19. import java.util.logging.SimpleFormatter;
  20. @SuppressWarnings("all")
  21. @RestController
  22. public class OssController {
  23. @Autowired
  24. OSS ossClient;
  25. @Value("${spring.cloud.alicloud.oss.endpoint}")
  26. private String endoint;
  27. @Value("${spring.cloud.alicloud.oss.bucket}")
  28. private String bucket;
  29. @Value("${spring.cloud.alicloud.access-key}")
  30. private String accessId;
  31. @RequestMapping("oss/policy")
  32. public R Policy() {
  33. // 填写Host地址,格式为https://bucketname.endpoint。
  34. String host = "https://" + bucket + "." + endoint;
  35. // 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
  36. String format = new SimpleDateFormat("yyyy:MM:hh").format(new Date());
  37. String dir = format + "/";
  38. Map<String, String> respMap = null;
  39. try {
  40. long expireTime = 6000;
  41. long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
  42. Date expiration = new Date(expireEndTime);
  43. PolicyConditions policyConds = new PolicyConditions();
  44. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
  45. policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
  46. String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
  47. byte[] binaryData = postPolicy.getBytes("utf-8");
  48. String encodedPolicy = BinaryUtil.toBase64String(binaryData);
  49. String postSignature = ossClient.calculatePostSignature(postPolicy);
  50. respMap = new LinkedHashMap<String, String>();
  51. respMap.put("accessid", accessId);
  52. respMap.put("policy", encodedPolicy);
  53. respMap.put("signature", postSignature);
  54. respMap.put("dir", dir);
  55. respMap.put("host", host);
  56. respMap.put("expire", String.valueOf(expireEndTime / 1000));
  57. } catch (Exception e) {
  58. System.out.println(e.getMessage());
  59. }
  60. return R.ok().put("data", respMap);
  61. }
  62. }

 以上是阿里云oss提供给的操作代码 自行修改就行了

前端步骤

链接:https://pan.baidu.com/s/15hQ2deh81-6ZAnAsUXt5Zg 
提取码:zxn4

三个文件放入到你的前端项目中 至于怎么组装到你的项目中去就看你是什么项目了 比如我这个是vue项目 我放入到src-->components下 然后再views里面去引入这个组件

 

 

下面就是你的后端请求路径先去后端通过base64加密的形式拿到你后端的 密钥 回调给客户端,客户端再拿着这个密钥和图片直接给oss 注意先拿密钥再推送图片过去,在action这里写入你的host(bucket+endpoint) 不然客户端拿到签名和图片不知道给谁了

  1. import http from '@/utils/httpRequest.js'
  2. export function policy() {
  3. return new Promise((resolve,reject)=>{
  4. http({
  5. url: http.adornUrl("/thirdparty/oss/policy"),
  6. method: "get",
  7. params: http.adornParams({})
  8. }).then(({ data }) => {
  9. resolve(data);
  10. })
  11. });
  12. }

有两个请求是因为 这里是跨域了 我做了跨域配置 会先有一个一模一样预检请求(options类型的请求),检查到没有跨域问题时,我的图片上传请求才开始(post类型的请求)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/702959
推荐阅读
相关标签
  

闽ICP备14008679号