在我的應用程式中,我想從 Firebase 存盤下載檔案(.pdf 和 .xls)。
我可以使用 生成下載鏈接ref.getDownloadURL(),但該鏈接會導致瀏覽器在下載或打開目標檔案之前打開一個新選項卡。
為了避免這種行為,我可以使用 javascript 下載檔案res = await fetch([the download URL]),然后await res.blob()
這作業正常:
const res = await fetch([downloadURL]);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = [file_name]; // e.g. my_file.xls
anchor.click();
但是,檔案建議我可以使用 SDK直接下載 blobgetBlob()
我試圖下載我的存盤桶中的檔案串列并遍歷這些檔案以獲取 blob,如下所示:
const storageRef = storage.ref().child("my_files");
const list = await storageRef.listAll();
const blob_array = await Promise.all(
list.items
.map(async (file) => {
const blob= await file.getBlob();
return {
name: file.name,
blob: blob,
};
})
);
但是,我收到一個錯誤:
型別錯誤:file.getBlob 不是函式
狀態的檔案getBlob():
要使用此功能,您必須在 Cloud Storage 存盤磁區中將應用的來源列入白名單。另請參閱 https://cloud.google.com/storage/docs/configuring-cors
為了對此進行測驗,我遵循了參考檔案,并使用 gsutil 為我的存盤桶設定了 CORS 策略,如下所示:
[
{
"origin": ["*"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]
我認為這會產生將我的應用程式來源“列入白名單”的效果(根據getBlob()檔案),但我仍然收到如下錯誤:
型別錯誤:file.getBlob 不是函式
如何啟用此getBlob()功能?
uj5u.com熱心網友回復:
問題正是錯誤所指出的 - 您試圖在沒有該方法的物件上呼叫 getBlob。
首先,查看下載檔案的檔案。它指出,從 SDK 9.5 版開始,就有一個全域 getBlob 函式。您沒有使用足夠新版本的 SDK 來獲得該功能。您使用的是舊版本 8,并且 Reference 物件沒有 getBlob 方法(掃描API 檔案 v8 以獲取 Reference,您將看不到它)。
如果要使用 getBlob,則必須升級到 v9 SDK并重寫所有 Firebase 代碼以符合新的 API。然后您將能夠使用新的 getBlob。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/484116.html
標籤:javascript 火力基地 谷歌云存储 gsutil
