javascript签名直传OSS

最近在写后台代码,使用的是VUE+ElementUI,踩了一些坑分享一下。

原理:从服务端获取签名,js直接上传阿里云OSS服务器。

elementui主要代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
template:

<el-form-item label="上传图片" prop="video">
<el-upload id="video" action
:data="aliyunOssToken"
:http-request="uploadVideo"
:headers="header">
<img v-if="form.cover" :src="form.cover">
<el-button class="avatar-uploader-icon" type="primary">上传</el-button>
</el-upload>
</el-form-item>


script:

upload(file){
var _self = this;
let imgType = file.file.type.split("/")[1].toLowerCase();
if (imgType != 'jpg' && imgType != 'png') {
this.$message.error('请上传图片类型');
return;
}
getOSSToken().then(function(res){
_self.aliyunOssToken = res.data;
var ossData = {};
//key就代表文件层级和阿里云上的文件名
let imgType = file.file.type.split("/")[1];
let filename = file.file.name + file.file.size; //md5对图片名称进行加密
let keyValue = "images/" + md5(new Date() + filename) + "." + imgType;

// 组装formdata
let formdata = new FormData();
formdata.append('name', file.file.name)
formdata.append('key', keyValue)
formdata.append('policy', _self.aliyunOssToken.policy)
formdata.append('OSSAccessKeyId', _self.aliyunOssToken.accessid)
formdata.append('success_action_status', 200)
formdata.append('signature', _self.aliyunOssToken.signature)
formdata.append('file', file.file)

_self.uploadOSS(formdata, _self.aliyunOssToken.host).then(function(res){
_self.form.cover = _self.aliyunOssToken.host + '/' + keyValue;
_self.$message.success('上传成功');
}).catch(function(error){
_self.$message.error('上传失败');
console.log(error);
})
}).catch(function(error){
console.log(error);
})
},
uploadOSS(formData, url) {
const config = {
headers: { "Content-Type": "multipart/form-data;boundary="+new Date().getTime() }
};
return axios.post(url,formData,config);
}

其中:务必使用表单提交方式,aliyunOssToken格式如下

1
2
3
4
5
6
7
8
{
"accessid": "LToofXWKudxfoAlI",
"host": "https:\/\/xxx.oss-cn-hangzhou.aliyuncs.com",
"policy": "eyJleHBpcmF0eretaW9uIjoiQxODowNzowMFoiLCJjb25kaXRpb25zIjpbWyJjb250ZW50LWxlbmd0aC17ewreMDQ4NTc2MDAwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsInZpZGVvXC8iXV19",
"signature": "HRFJ4345VIvRhrsMa44546=",
"expire": 1578478020,
"dir": "images\/"
}

记得设置阿里云OSS跨域规则:

跨域规则

文档: