【问题标题】:How to Delete Image from Firebase cloud Storage - REACT如何从 Firebase 云存储中删除图像 - REACT
【发布时间】:2022-01-09 11:40:48
【问题描述】:

我的Storage Post/ID/image.jpg 中有以下结构。 Post 和 ID 是可以轻松找到的文件夹,但 ID 可能包含多个图像。我怎么可能删除所有这些? 在我的代码中,我有一个函数应该删除 firestore database 中的帖子并删除 firebase storage 中的图像引用

抛出的错误是:

TypeError: Cannot read properties of undefined (reading '_throwIfRoot')

删除函数

const DeletePost = async (e) => {
    e.preventDefault();
    const querySnapshot = await getDocs(collection(db, `${category}Posts`));
    querySnapshot.forEach((docx) => {
        if (post.AdTitle === docx.data().AdTitle) {
            try {
                deleteObject(ref(storage, `${category}Posts`, docx.id).child);
                deleteDoc(doc(db, `${category}Posts`, docx.id));
            } catch (error) {
                console.log("error in delete image, " + error);
            }
            // router.reload();
        }
    });
};

编辑

【问题讨论】:

    标签: javascript reactjs firebase firebase-storage


    【解决方案1】:

    StorageReference 上没有任何 child 属性。尝试删除它,如下所示:

    deleteObject(ref(storage, `${category}Posts`, docx.id + ".ext")) // .child);
    
    // Make sure you add the file extension at the end
    

    deleteObject()deleteDoc 也都返回一个承诺,结帐也是如此:Using async/await with a forEach loop

    【讨论】:

    • 我第一次尝试没有孩子但我收到以下错误:FirebaseError: Firebase Storage: Object 'ElectroniquePosts' does not exist. (storage/object-not-found)
    • @Laspeed 您可以分享您要删除的文件的屏幕截图(确保路径可见)吗?还有console.log(docx.id) 并分享输出?
    • 请检查编辑@Dharmaraj
    • @Laspeed 您确实需要在参考文献中添加文件扩展名。检查我的更新答案
    • 仍然得到:Firebase 存储:对象“ElectroniquePosts”不存在。 (存储/未找到对象)
    【解决方案2】:

    documentation 之后,我终于想出了一个可行的解决方案,这是更新后的代码。

    try {
        const listRef = ref(storage, `${category}Posts/${docx.id}/`);
        listAll(listRef)
          .then((res) => {
            res.items.forEach((itemRef) => {
              setValues((prevState) => [...prevState, itemRef]);
            });
            if (values !== "") {
              console.log("attempting");
              values?.map((value) =>
                deleteObject(
                  ref(storage, `${category}Posts/${docx.id}/${value.name}`)
                ).then(() => {
                  console.log("storage success");
                })
              );
    
              deleteDoc(doc(db, `${category}Posts`, docx.id)).then(() => {
                console.log("doc success");
                router.reload();
              });
            }
          })
          .catch((error) => {
            console.log("error : " + error);
          })
    

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2021-07-24
      • 2019-12-15
      • 2020-10-22
      • 2018-03-15
      • 2021-04-25
      相关资源
      最近更新 更多