网上的文章很少有使用STS来上传文件到OSS的,比如这个开源代码库:
https://github.com/peterhuang007/weixinFileToaliyun
使用这上面的方法在小程序上传文件,会一直提示错误:
The OSS Access Key Id you provided does not exist in our records.
原因是需要长期有效的AccessKeyId,而我们项目使用的是临时有效的AccessKeyId,所以会提示无效的Id。
google了很多文章,都没有详细描述STS策略下如何访问,最后在官方找到一篇文章(点我)作为参考,试验成功了,在此记录一下,以节省其他人时间。
重点:
在表单中添加"x-oss-security-token"域,值为临时有效的token,签名也用临时有效的AccessSecret来生成。
而这篇官方文章(点我)说在header中添加的做法是错误的,也有可能这篇文章说的场景不是Post Object,我个人理解有误。
还是用代码表达更清楚,上代码(签名代码取自上面的github开源库):
https://github.com/peterhuang007/weixinFileToaliyun
使用这上面的方法在小程序上传文件,会一直提示错误:
The OSS Access Key Id you provided does not exist in our records.
原因是需要长期有效的AccessKeyId,而我们项目使用的是临时有效的AccessKeyId,所以会提示无效的Id。
google了很多文章,都没有详细描述STS策略下如何访问,最后在官方找到一篇文章(点我)作为参考,试验成功了,在此记录一下,以节省其他人时间。
重点:
在表单中添加"x-oss-security-token"域,值为临时有效的token,签名也用临时有效的AccessSecret来生成。
而这篇官方文章(点我)说在header中添加的做法是错误的,也有可能这篇文章说的场景不是Post Object,我个人理解有误。
还是用代码表达更清楚,上代码(签名代码取自上面的github开源库):
const aliyunFileKey = res.data.data.fileKey;
const accessToken = res.data.data.accessToken;
const bucket = res.data.data.bucket;
const aliyunServerURL = 'https://' + bucket + '.' + res.data.data.endpoint;
const accessSecret = res.data.data.accessSecret;
const accessKeyId = res.data.data.accessKeyId;
const policyBase64 = getPolicyBase64(res.data.data.expiration);
const signature = getSignature(policyBase64, accessSecret);
wx.uploadFile({
url: aliyunServerURL,
filePath: filePath,
name: 'file',
header: {},
formData: {
'key': aliyunFileKey,
'OSSAccessKeyId': accessKeyId,
'policy': policyBase64,
'Signature': signature,
'success_action_status': '200',
'x-oss-security-token': accessToken, //这个对STS策略来说是最重要的
},
success: function (res) {
if (res.statusCode != 200) {
failBlock(new Error(JSON.stringify(res)))
return;
}
console.log('upload success: ', res)
successBlock(aliyunFileKey);
},
fail: function (err) {
err.wxaddinfo = aliyunServerURL;
failBlock(err);
},
});
评论
发表评论