ElementUI的upload上传文件到OSS,使用授权URL,无需额外配置RAM账户
ElementUI的upload上传文件到OSS,使用授权URL,无需额外配置RAM账户
最近在做一个上传到oss的部分,oss文档中使用sts授权的方式阅读量太大,不想看。
授权URL的方式看上去更加简单,于是开始研究。但是这一部分网上相关案例是真的少,经过好久的调试,现在将代码贴出来
1.服务器端
//oss的配置,这个不介意的话直接用主账号的也没关系,权限做的好点的就自己创建一个ram用户
let ossConfig={
"region": "oss-cn-xxxx",
"accessKeyId": "LTxxxxxxxxxxxxxxxxxxxx",
"accessKeySecret": "fcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"bucket": "xxx"
}
//获取授权URL,源文档 https://help.aliyun.com/document_detail/32077.html#title-sdv-594-iub
const client = new OSS(ossConfig);
let filename='xxxxx.zip';
const url = client.signatureUrl(filename, {
expires: 3600,
method: 'PUT',
'Content-Type': 'application/octet-stream',//这里与原文档不同,源文档是'text/plain; charset=UTF-8'类型,这里很重要
});
console.log(url)
//这个URL回传到前端
2.前端
el-upload组件中
el-upload#(
action='',//这里很重要,这里必须留空,且配合下方的http-request才能覆盖默认上传方法
:http-request='upload',//upload是自定义的上传方法
:auto-upload='true')//这个我个人喜欢自动上传,必须换点击,这里不重要
自定义的upload方法
upload: function (param) {
let that = this
that
.$axios({
method: 'put',
url: that.uploadUrl,//后端传过来的授权url
data: param.file,//这里很重要,必须直接使用param.file,
//很多教程使用的是formData嵌套了一遍,那么在上传的时候,
//content-type就会变成multipart/form-data; boundary=----WebKitFormBoundaryaskldjlkasjdlk这样子的,
//关键在于这个自动附上的boundary,这个部分我们在申请授权url的时候并没有带上,也带不上,所以会导致申请的url的签名与实际上传时候计算的签名不一致,然后被oss403掉。
//所以这里一定要这样子
withCredentials: false,//跨域必须
headers: {
'Content-Type': 'application/octet-stream',//这里上面写了,很重要
}
})
.then(function (response) {
//成功
})
.catch(function (error) {
//报错
})
},
总结
最重要的就是申请URL和实际上传时候的header必须一模一样,而使用formData会自动附上boundary导致签名校验失败