Firebase存储无法上传任何文件

时间:2018-10-23 08:06:14

标签: firebase storage

当我尝试将任何图像文件上传到Firebase Storage时,我收到一条错误消息。

Object { code_: "storage/unauthorized", message_: "Firebase Storage: User does not have permission to access 'img/product/1540281542536/58916.jpg'.", serverResponse_: "{\n  \"error\": {\n    \"code\": 403,\n    \"message\": \"Permission denied. Could not perform this operation\"\n  }\n}", name_: "FirebaseError" }

我不知道为什么它不起作用

这是我的存储规则

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      match /img {
        match /{allImages=**} {
            allow read
        }
        match /product/{productID}/{imageId} {
            allow create, write, delete: if request.auth != null
        }
      }
      match /user/{userId} {
        allow read, write: if request.auth.uid == userId;
      }
    }
  }
}

这是我的上传代码

$formImgUpload.on('change', function (e) {
  let file = this.files[0]
  let rootRef = firebase.storage().ref()
  let fileName = 'img/product/' + id + '/' + file.name
  let fileRef = rootRef.child(fileName)

  fileRef.put(file).then(function (result) {
    console.log('"' + fileName + '" was uploaded successfully.')

    result.ref.getDownloadURL().then(function (url) {
      $img.attr('src', url)
      $fileUrl.text(url)
    })
  }).catch(function (err) {
    console.error(err)
  })
})

有人可以帮助我编写正确的规则吗?

1 个答案:

答案 0 :(得分:0)

我也有这个问题。您是从客户上传吗?如果是这样,目前您没有为request.auth发送任何内容,因此它将始终为null。

要解决此问题,请发送自定义令牌-> https://firebase.google.com/docs/auth/admin/create-custom-tokens

使用Firebase Admin SDK创建自定义令牌是一种非常简单的方法,使用您的UID从服务器发送令牌,然后在客户端进行身份验证。然后,当您将数据发送到Storage时,request.auth随之出现,然后数据库规则将能够处理这种情况。

希望这会有所帮助。

祝一切顺利。