我正在嘗試獲取 firebase 存盤中檔案的下載 url。
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。如何獲得正確的下載網址?
uj5u.com熱心網友回復:
上傳檔案后,您必須使用函式getDownloadURL()向存盤發送請求以獲取 downloadURL。這是因為資料庫正在向檔案添加令牌,因此無需登錄就可以下載檔案。功能uploadBytes()是寫入操作而不是讀取,因此出于安全原因,您有單獨的功能可以從存盤中獲取/讀取 downloadURLs。
這里有打字稿中的函式示例。它上傳檔案陣列并回傳物件陣列:{ 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/378842.html
標籤:javascript 火力基地 火力存储
