Home > Software design >  Firebase 9 Web: how do I get download url for stored files?
Firebase 9 Web: how do I get download url for stored files?

Time:12-11

I'm trying to get download urls for files in firebase storage.

const listRef = ref(storage, `photos/${route.params.id}`)

onMounted( async () => {
  await listAll(listRef)
    .then((res) => {
      res.items.forEach( (item) => {
        console.log(item._location)
      })
    }).catch((error) => {
      console.log(error)
    })
})

I can just find path in the response object, which I can't use as an img src. How can I get a proper download url?

CodePudding user response:

After you upload files you have to send request using function getDownloadURL() to a storage to get downloadURL. It is because of database are adding tokens to files so there is possibility to download files with no need to be logged in. Function uploadBytes() is write operation not read so for security reason you have separate function to get/read downloadURLs from storage.

Here you have function example in typescript. It upload array of files and return array of objects: { name: string, fullPath: string, downloadURL: string }.

async function uploadFiles(path: string, files: File[], id: string) {
    if (!files.length) return []
    const promises = []
    const data = []
    for (const item of files) {
        const storageRef = ref(storage, `${path}/${id}_${item.name}`)
        promises.push(uploadBytes(storageRef, item))
    }
    const uploadResults = await Promise.all(promises)
    const downloadURLs = []

    for (const item of uploadResults) {
        data.push({ fullPath: item.metadata.fullPath, downloadURL: '', name: '' })
        downloadURLs.push(getDownloadURL(item.ref))
    }

    const downloadURLsResult = await Promise.all(downloadURLs)

    for (var i = 0; i < downloadURLsResult.length; i  ) {
        data[i].downloadURL = downloadURLsResult[i]
        data[i].name = files[i].name
    }

    return data
}
  • Related