小程序上传图片到阿里oss之后报403?

张巨侠
  • 359

image.png
OSSAccessKeyId和accessKeySecret从服务器获取。
signature和policy是前端生成的,
这是请求参数
image.png
这是代码

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
}
回复
阅读 551
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏