# 阿里云OSS回调上传(二)
## Intro
[项目阿里云OSS实现上传的文档](http://www.macrozheng.com/#/architect/mall_arch_10) ,接着之前一篇文章《SpringBoot+阿里云OSS上传回调》讲到,调用Post请求,响应结果`500错误`。原因探查许久,也没名外为什么出错。有可能请求超时,也有可能服务器内部错吧。这次尝试不同的实现方案。一探究竟吧!
如果您不知道OSS,建议您先去阿里云OSS[官方文档学习](https://help.aliyun.com/product/31815.html)。
## 后端实现
利用IDEA,使用Spring Initializer构建项目,使用Maven构建依赖。
- pom.xml配置文件 核心部分配置
```xml
<properties>
<!--jdk版本-->
<java.version>1.8</java.version>
<!--spring-cloud版本-->
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
<!--oss依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>
<!-- web应用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!--版本控制-->
<dependencyManagement>
<dependencies>
<!-- springcloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- spring-cloud-alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
```
application.yaml
```yml
spring:
cloud:
alicloud:
access-key: LTAI5tS1dbXZ5XXXXXXXXX
secret-key: VEcT4rYx1HDyZoXXXXXXXXXXXXXXXXX
oss:
endpoint: oss-cn-beijing.aliyuncs.com
bucket: zhoujk-mall
#应用名称
application:
name: SpringBoot-OSS-Callback
#端口
server:
port: 8888
```
之后,需要设置配置类。CorsConfig以实现跨域,当然,也可以在阿里云OSS控制台中进行设置。
```java
package com.zhoujk.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author : zhoujiankang
* @Desc:实现基本的跨域请求
* @since : 2022/4/5 11:01
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
/*是否允许请求带有验证信息*/
corsConfiguration.setAllowCredentials(true);
/*允许访问的客户端域名*/
corsConfiguration.addAllowedOrigin("*");
/*允许服务端访问的客户端请求头*/
corsConfiguration.addAllowedHeader("*");
/*允许访问的方法名,GET POST等*/
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
```
![image-20220406154337448](https://mybolg-typora.oss-cn-beijing.aliyuncs.com/image-20220406154337448.png)
例如,允许Post请求进行跨域。
Controller类
```java
@RestController
public class OSSController {
@Resource
@Autowired(required = false)//单纯去掉红色下划线,强迫症
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 Map<String, String> policy() {
String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
// callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String callbackUrl = "http://88.88.88.88:8888";
String dir = format + "/"; // 用户上传文件时指定的前缀。
Map<String, String> respMap = null;
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
// PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
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));
// respMap.put("expire", formatISO8601Date(expiration));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
} finally {
ossClient.shutdown();
}
System.out.println("respMap:" + respMap);
return respMap;
}
}
```
## 前端实现
Vue实现上传
```vue
<!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=" https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<!-- 引入样式 (element ui) -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库(element ui)-->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<!-- axios发送异步请求 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<!-- 上传的组件 -->
<div>
<el-upload action="https://zhoujk-mall.oss-cn-beijing.aliyuncs.com"
:data="dataObj"
list-type="picture"
:multiple="false"
:show-file-list="showFileList"
:file-list="fileList"
:before-upload="beforeUpload"
:on-remove="handleRemove"
:on-success="handleUploadSuccess"
:on-preview="handlePreview">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过10MB</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="fileList[0].url" alt="">
</el-dialog>
</div>
</div>
</body>
<script type="text/javascript">
//实例化vue
new Vue({
el: '#app',
props: {
value: String
},
computed: {
imageUrl() {
return this.value;
},
imageName() {
if (this.value != null && this.value !== '') {
return this.value.substr(this.value.lastIndexOf("/") + 1);
} else {
return null;
}
},
fileList() {
return [{
name: this.imageName,
url: this.imageUrl
}]
},
showFileList: {
get: function () {
return this.value !== null && this.value !== '' && this.value !== undefined;
},
set: function (newValue) {}
}
},
data() {
return {
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: '',
// callback:'',
},
dialogVisible: false
};
},
methods: {
emitInput(val) {
this.$emit('input', val)
},
handleRemove(file, fileList) {
this.emitInput('');
},
handlePreview(file) {
this.dialogVisible = true;
},
beforeUpload(file) {
let _self = this;
return new Promise((resolve, reject) => {
new Promise((resolve, reject)=>{
axios({
url: "http://localhost:8888/oss/policy",
methods: 'get',
//参数
//params:{ }
}).then(({data}) => {
console.log("签名数据:",data);
resolve(data);
})
}).then(response => {
_self.dataObj.policy = response.policy;
_self.dataObj.signature = response.signature;
_self.dataObj.ossaccessKeyId = response.accessid;
_self.dataObj.key = response.dir + this.getUUID() + '_${filename}';
_self.dataObj.dir = response.dir;
_self.dataObj.host = response.host;
resolve(true)
}).catch(err => {
reject(false)
console.log("失败",err);
})
})
},
handleUploadSuccess(res, file) {
console.log("上传成功...")
this.showFileList = true;
this.fileList.pop();
this.fileList.push({
name: file.name,
// 上传成功后图片路劲
url: this.dataObj.host + '/' + this.dataObj.key.replace("${filename}", file.name)
});
console.log("访问地址:",this.fileList[0].url);
this.emitInput(this.fileList[0].url);
},
//生成uuid
getUUID () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
}
}
});
</script>
</html>
```
来看一看实现效果吧。
![image-20220406155747815](https://mybolg-typora.oss-cn-beijing.aliyuncs.com/image-20220406155747815.png)
**接口文档**
![image-20220406215904386](https://mybolg-typora.oss-cn-beijing.aliyuncs.com/image-20220406215904386.png)
![image-20220406220008444](https://mybolg-typora.oss-cn-beijing.aliyuncs.com/image-20220406220008444.png)
[输入密码查看全部接口文档](https://docs.apipost.cn/preview/8cc13cc20059a390/a800c6b6c5156a8f)
阿里云OSS回调上传(二)