【问题标题】:uploading and retrieving image from firebase从firebase上传和检索图像
【发布时间】:2021-07-26 20:37:20
【问题描述】:

我正在使用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)
      );

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

获取图片错误的下载 URL => [FirebaseError: Firebase Storage: Object 'userId' 不存在。 (存储/未找到对象)]

我在这里做错了什么?

【问题讨论】:

    标签: javascript firebase react-native firebase-storage


    【解决方案1】:

    错误消息说在您调用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);
    

    【讨论】:

    • 谢谢,我看错了位置,再次感谢,但是为什么不再使用孩子呢?
    • 如果你愿意,你可以对child 做同样的事情。不会有任何区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2020-01-17
    • 2016-02-12
    • 2021-06-23
    • 1970-01-01
    • 2017-12-17
    • 2020-08-05
    相关资源
    最近更新 更多