从 firebase 上传和检索图像

uploading and retrieving image from firebase

我正在使用 firebase 将用户的照片上传到数据库中,我结合使用了 expo 图像选择器,代码如下:

    const handleImagePicked = async (pickerResult) => {
        console.log("here");
        if (!pickerResult.cancelled) {
          setImage(pickerResult.uri);
          const result = await uploadImageAsync(pickerResult.uri);
          if (result) {
            console.log("success");
            return;
          }
          alert("Upload failed, sorry :(");
        }
      };
    
      async function uploadImageAsync(uri) {
        const blob = await new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.onload = function () {
            resolve(xhr.response);
          };
          xhr.onerror = function (e) {
            console.log(e);
            reject(new TypeError("Network request failed"));
          };
          xhr.responseType = "blob";
          xhr.open("GET", uri, true);
          xhr.send(null);
        });
    
  const ref = firebase
      .storage()
      .ref(uid)
      .child("/profile_pictures/" + uid);

    
        const snapshot = await ref.put(blob);
   
        blob.close();
   
        const userRef = db.collection("users").doc(uid);
        const res = await userRef.update({ photo: snapshot });
        return await snapshot.ref.getDownloadURL();
      }

这工作正常,我可以在我的 firebase 中看到在存储下创建了一个新文件夹,里面有用户上传的图像。

要在不同的屏幕上检索图像,我就是这样做的:

let imageRef = firebase.storage().ref(userId);
    imageRef
      .getDownloadURL()
      .then((url) => {
        setImage({ profileImageUrl: url });
      })
      .catch((e) =>
        console.log("getting downloadURL of image error => ", e)
      );

但是,当我访问我的个人资料页面时,它没有显示图像,因为它告诉我有一个错误:

getting downloadURL of image error => [FirebaseError: Firebase Storage: Object 'userId' does not exist. (storage/object-not-found)]

我做错了什么?

错误消息说您调用 getDownloadURL 的位置不存在文件。从代码来看,这是有道理的。

您将图片上传至:

firebase
      .storage()
      .ref(uid)
      .child("/profile_pictures/" + uid);

您尝试从以下位置下载 URL:

firebase.storage().ref(userId);

那是两个不同的地点。第一个指向 /$uid/profile_pictures/$uid,而第二个只指向 /$uid。您应该在两个地方都使用对同一路径的引用,我的建议是对两者都使用:

firebase
      .storage()
      .ref("/profile_pictures/" + uid);