【问题标题】:Firebase 9 Web: how do I get download url for stored files?Firebase 9 Web:如何获取存储文件的下载网址?
【发布时间】:2022-01-15 04:51:45
【问题描述】:
我正在尝试获取 Firebase 存储中文件的下载网址。
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)
})
})
我只能在响应对象中找到路径,我不能将其用作 img src。如何获得正确的下载地址?
【问题讨论】:
标签:
javascript
firebase
firebase-storage
【解决方案1】:
上传文件后,您必须使用函数getDownloadURL() 向存储发送请求以获取下载URL。这是因为数据库正在向文件添加令牌,因此可以下载文件而无需登录。函数uploadBytes() 是写入操作而不是读取,因此出于安全原因,您有单独的函数从存储中获取/读取下载 URL。
这里有打字稿中的函数示例。它上传文件数组并返回对象数组:{ 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
}