使用 Cloud Storage 網頁版下載檔案

Cloud Storage for Firebase 可讓您從 Firebase 提供及管理的 Cloud Storage bucket 輕鬆快速下載檔案。

可建立參照

如要下載檔案,請先建立 Cloud Storage 參照,指向要下載的檔案。

您可以將子路徑附加至 Cloud Storage bucket 的根目錄,藉此建立參照,也可以從現有的 gs://https:// 網址建立參照,該網址參照 Cloud Storage 中的物件。

Web

import { getStorage, ref } from "firebase/storage";

// Create a reference with an initial file path and name
const storage = getStorage();
const pathReference = ref(storage, 'images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
const gsReference = ref(storage, 'gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
const httpsReference = ref(storage, 'https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

Web

// Create a reference with an initial file path and name
var storage = firebase.storage();
var pathReference = storage.ref('images/stars.jpg');

// Create a reference from a Google Cloud Storage URI
var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg');

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');  

透過網址下載資料

如要取得檔案的下載網址,請對 Cloud Storage 參照呼叫 getDownloadURL() 方法。

Web

import { getStorage, ref, getDownloadURL } from "firebase/storage";

const storage = getStorage();
getDownloadURL(ref(storage, 'images/stars.jpg'))
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    const xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      const blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    const img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

Web

storageRef.child('images/stars.jpg').getDownloadURL()
  .then((url) => {
    // `url` is the download URL for 'images/stars.jpg'

    // This can be downloaded directly:
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = (event) => {
      var blob = xhr.response;
    };
    xhr.open('GET', url);
    xhr.send();

    // Or inserted into an <img> element
    var img = document.getElementById('myimg');
    img.setAttribute('src', url);
  })
  .catch((error) => {
    // Handle any errors
  });

直接從 SDK 下載資料

自 9.5 以上版本起,SDK 提供下列函式,可直接下載:

使用這些函式時,您可以略過從網址下載的步驟,直接在程式碼中傳回資料。透過 Firebase Security Rules,您可以更精細地控管存取權。

CORS 設定

如要在瀏覽器中直接下載資料,請為 bucket 設定跨源存取 (CORS)。Cloud Storage您可以使用 gsutil 指令列工具完成這項作業,請按這裡安裝

如果您不希望有任何網域限制 (最常見的情況),請將下列 JSON 複製到名為 cors.json 的檔案:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

執行 gsutil cors set cors.json gs://<your-cloud-storage-bucket> 部署這些限制。

詳情請參閱 Google Cloud Storage 說明文件

處理錯誤

下載時發生錯誤的原因有很多,包括檔案不存在,或是使用者沒有存取所需檔案的權限。如要進一步瞭解錯誤,請參閱文件中的「處理錯誤」一節。

完整範例

以下是包含錯誤處理機制的完整下載範例:

Web

import { getStorage, ref, getDownloadURL } from "firebase/storage";

// Create a reference to the file we want to download
const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

// Get the download URL
getDownloadURL(starsRef)
  .then((url) => {
    // Insert url into an <img> tag to "download"
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the upload
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect the server response
        break;
    }
  });

Web

// Create a reference to the file we want to download
var starsRef = storageRef.child('images/stars.jpg');

// Get the download URL
starsRef.getDownloadURL()
.then((url) => {
  // Insert url into an <img> tag to "download"
})
.catch((error) => {
  // A full list of error codes is available at
  // https://firebase.google.com/docs/storage/web/handle-errors
  switch (error.code) {
    case 'storage/object-not-found':
      // File doesn't exist
      break;
    case 'storage/unauthorized':
      // User doesn't have permission to access the object
      break;
    case 'storage/canceled':
      // User canceled the upload
      break;

    // ...

    case 'storage/unknown':
      // Unknown error occurred, inspect the server response
      break;
  }
});

您也可以取得或更新儲存在 Cloud Storage 中的檔案中繼資料。