文章目录
- 1.单体前后端项目上传
- 1.上传流程
- 2. BuckName 和EndPoint
- 3. AccessKey 和Access Secret(创建RAM(Resource Access Manage)的子账号,然后可以获得Accesskey和Acess Secret)
- 3.根据创建的子账号分配OSS的所有权限(可以对文件进行上传,下载,删除的权限)
- 4.采用上传的方式(服务器直传,服务器得签名后后端直传,前端直传)
- 5. 出现跨域问题解决
- 引入依赖
- 6.前端实现code
- 7.后端code实现
- 2.SpringCloud形式OSS上传
- 1.引入依赖
- 2.后端实现code
- 3.前端实现code
1.单体前后端项目上传
1.上传流程
这样有利于保护自己的账号和密码不被泄露,通过账号密码生成的防伪笔名进行验证是否正确
2. BuckName 和EndPoint
3. AccessKey 和Access Secret(创建RAM(Resource Access Manage)的子账号,然后可以获得Accesskey和Acess Secret)
3.根据创建的子账号分配OSS的所有权限(可以对文件进行上传,下载,删除的权限)
4.采用上传的方式(服务器直传,服务器得签名后后端直传,前端直传)
前端直传:不好,用户可以直接f12找到我们的endpoint,bucketName,和重要的Acesskey,AccessSecret,不安全,导致我们的信息泄露。
服务器直传:会造成性能瓶颈,给服务器造成压力。
服务器得签名后后端直传:这种方法可以,可以加密我们的签名之后进行上传。如果想了解用户上传了什么东西可以设计 上传回调
5. 出现跨域问题解决
引入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.0</version>
</dependency>
<dependency>
6.前端实现code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>oss测试上传</title>
<script src="static/js/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<!-- <form action="/upload/oss" method="post" enctype="multipart/form-data">
<input type="file" name="file" value="选择文件上传">
<input type="submit" name="提交"/>
</form> -->
<el-upload
draggable="true"
class="upload-demo"
:action="obj.host"
:before-upload="ossPolicy"
:on-success="onsuccess"
//上传时绑定的数据
:data="obj"
:limit="2"
:file-list="fileList"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
<script src="static/js/axios.min.js"></script>
<script type="text/javascript ">
var vm=new Vue({
el:"#app",
data:{
fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
obj:{
OSSAccessKeyId:"",
policy:"",
signature:"",
key:"",
host:"",
dir:"",
}
},
methods: {
ossPolicy(file){
// 上传前,获取服务器给的签名
axios({
url:"http://localhost:8080/oss/policy",
method:"get",
}).then(res=>{
console.log("come in ---------",res.data)
this.obj.OSSAccessKeyId = res.data.accessId;
this.obj.policy = res.data.policy;
this.obj.dir = res.data.dir;
this.obj.signature = res.data.signature;
//传到oss的服务器地址
this.obj.host = res.data.host;
this.obj.key =res.data.dir + "${filename}";
})
},
//文件上传成功时调用
onsuccess(response, file, fileList){
console.log("response",response)
console.log(file)
},
}
})
</script>
</body>
</html>
7.后端code实现
package com.qfedu.fmmall.controller;/*
**
*@author SmallMonkey
*@Date 2023/2/10 13:07
*
*
**/
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
@RestController
@CrossOrigin
@RequestMapping("/oss")
public class OssController {
@RequestMapping("/policy")
public Map<String,String> policy(){
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessId = "LTAI5tRNby21a72dAhf4NbPa";
String accessKey = "LTWOauYIuCkNF2O9zgU0Mm7HCuV5BE";
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 填写Bucket名称,例如examplebucket。
String bucket = "fmmallrebuild";
// 填写Host地址,格式为https://bucketname.endpoint。
String host = "https://" + bucket + "." + endpoint;
// 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
// String callbackUrl = "https://192.168.0.0:8888";
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
//可以加上当前的日期
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dir = simpleDateFormat.format(new Date()) + "/";
//String objectName = dir + UUID.randomUUID().toString()+".png";
// 创建ossClient实例。
OSS ossClient = new OSSClientBuilder().build(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));
return respMap;
//服务进行上线之后,有一个外网可以访问的地址可以设置回调
/*
JSONObject jasonCallback = new JSONObject();
jasonCallback.put("callbackUrl", callbackUrl);
jasonCallback.put("callbackBody",
"filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
respMap.put("callback", base64CallbackBody);
JSONObject ja1 = JSONObject.fromObject(respMap);*/
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return null;
}
}
2.SpringCloud形式OSS上传
1.引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
2.后端实现code
@RestController
public class OssController {
@Autowired
OSS ossClient;
@Value ("${spring.cloud.alicloud.oss.endpoint}")
String endpoint ;
@Value("${spring.cloud.alicloud.oss.bucket}")
String bucket ;
@Value("${spring.cloud.alicloud.access-key}")
String accessId ;
@Value("${spring.cloud.alicloud.secret-key}")
String accessKey ;
@RequestMapping("/oss/policy")
public Map<String, String> policy(){
String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
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) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
} finally {
ossClient.shutdown();
}
return respMap;
}
}