Firebase 9 Web:如何下载 url 存储的文件?
Firebase 9 Web: how do I get download url for stored files?
我正在尝试为 Firebase 存储中的文件下载 urls。
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。我怎样才能得到正确的下载url?
上传文件后,您必须使用函数 getDownloadURL()
向存储发送请求以获取下载 URL。这是因为数据库正在向文件添加令牌,因此有可能无需登录即可下载文件。函数 uploadBytes()
是写入操作而不是读取,因此出于安全原因,您有单独的函数 get/read从存储中下载 URL。
这里有打字稿中的函数示例。它上传文件数组和 return 对象数组:{ 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
}
我正在尝试为 Firebase 存储中的文件下载 urls。
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。我怎样才能得到正确的下载url?
上传文件后,您必须使用函数 getDownloadURL()
向存储发送请求以获取下载 URL。这是因为数据库正在向文件添加令牌,因此有可能无需登录即可下载文件。函数 uploadBytes()
是写入操作而不是读取,因此出于安全原因,您有单独的函数 get/read从存储中下载 URL。
这里有打字稿中的函数示例。它上传文件数组和 return 对象数组:{ 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
}