How to get a reference to firebase image to be able to delete it?

*爱你&永不变心* 提交于 2020-06-16 17:24:29

问题


so I have this function to retrieve all my photos

const getPhotos = async () => {
    const storage = firebaseApp.storage()
    let gsReference = storage.refFromURL('gs://my-app/')
    gsReference = gsReference.child(`${id}/${country}`)

    const { items } = await gsReference.listAll()
    const urlPromises = items.map((pr) =>
        pr
            .getDownloadURL()
            .then((url) => fetch(url))
            .catch((error) => error),
    )

    let urls = await Promise.all(urlPromises)
    urls = urls.filter((result) => !(result instanceof Error))
    setPhotos(urls)
}

this works all good

now the problem is when I want to delete an image. ive got this function

const deletePhoto = (photoRef) => {
    console.log('PHOTO:', photoRef)
    var storage = firebaseApp.storage()
    var storageRef = storage.ref(`${id}/${country}`)
}

the problem is I have no way of knowing the reference to the image I want to delete?

I am mapping over all the images and for each image I'm attaching the delete function and passing in the photo as an arg. however this just returns me this

body: ReadableStream {locked: false}
bodyUsed: false
headers: Headers {append: function, delete: function, get: function, has: function, set: 
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://firebasestorage.googleapis.com/v0/b/my-app.appspot.com/o/F2DFB6714-8082-4AF9-89…"

it looks like the url does reference the path but it cuts some of it off at the end. plus I don't really want to be splicing that down to find the image. there must be an easy way to set the reference??


回答1:


You can combine Response and Reference object in another then callback after catch.

const getPhotos = async () => {
    const storage = firebaseApp.storage()
    let gsReference = storage.refFromURL('gs://my-app/')
    gsReference = gsReference.child(`${id}/${country}`)

    const { items: references } = await gsReference.listAll()
    const result = references.map(async (reference) => {
        const url = await reference.getDownloadURL();
        let response = null;

        try {
           response = await fetch(url);
        }
        catch(error) {
           response = error;
        }

        return {
           response,
           url,
           reference
        }
      }
    )

    let referencesWithUrls = await Promise.all(result)
    referencesWithUrls = referencesWithUrls.filter((result) => !(result.response instanceof Error))
    setPhotos(referencesWithUrls.map(pr => pr.response))
}


来源:https://stackoverflow.com/questions/62149482/how-to-get-a-reference-to-firebase-image-to-be-able-to-delete-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!