Wonderjar's Blog

前端直传文件到阿里OSS

2018-08-26

将accessToken放在前端的方案不提,因为不安全
后端签名提供一个这样的signedObj,然后前端就可以完成上传

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
var signedObj = {
OSSAccessKeyId: "XXX"
dir:"XXX/",
expire:XXX,
host:"http://oss-cn-beijing.aliyuncs.com"
policy:"XXX"
signature:"XXX"
}

// key指定完整的文件路径
signedObj['key'] = signedObj['dir'] + '/' + "${filename}"
// 否则默认成功返回204,不太喜欢
signedObj['success_action_status'] = 201

var formData = new FormData();

for(const key in signedObj) {
formData.append(key, signedObj[key])
}

//file要放最后
formData.append("file", file)

http.post('http://oss-cn-beijing.aliyuncs.com/XXX', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});

阿里OSS返回xml格式,可以正则简单提取一下

1
2
const reg = /<Location>([\s\S]+)<\/Location>/gi
const newFilePath = reg.exec(result)[1]