小程序上传图片到阿里oss之后报403?
OSSAccessKeyId和accessKeySecret从服务器获取。
signature和policy是前端生成的,
这是请求参数
这是代码
handleUpload = async (files:any) => {
Taro.showToast({title: '上传中'})
let { dir, ossToken } = this.state
const policyBase64 = this.getPolicyBase64()
const signature = this.getSignature(policyBase64)
console.log('ossToken', ossToken)
let newArr = files.map((item:any) => {
let formData = {
key: dir + item.substring(item.lastIndexOf('/')+1),
policy: policyBase64,
OSSAccessKeyId: (ossToken as any).accessKeyId,
signature,
success_action_status: '200'
}
console.log('formData', formData)
return Taro.uploadFile({
url: (ossToken as any).filePath,
filePath: item,
header: {
"Content-Type": "multipart/form-data"
},
name: 'file',
formData
})
})
let resArr = await Promise.all(newArr)
Taro.hideLoading()
console.log(resArr)
}
getPolicyBase64 = ():string => {
let date = new Date();
date.setHours(date.getHours() + 700 * 1000);
let srcT = date.toISOString();
const policyText = {
"expiration": srcT, //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了
"conditions": [
["content-length-range", 0, 5*1024 * 1024] // 设置上传文件的大小限制,5mb
]
};
const policyBase64 = Base64.encode(JSON.stringify(policyText));
return policyBase64
}
getSignature = (policyBase64:string) => {
let { ossToken } = this.state
const accesskey = (ossToken as any).accessKeySecret
const signature = Crypto.enc.Base64.stringify(Crypto.HmacSHA1(accesskey, policyBase64))
console.log(signature)
return signature
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论