使用 Cloud Storage 網頁版下載檔案

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

可建立參照

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

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

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 設定

如要在瀏覽器中直接下載資料,您必須為 Cloud Storage 值區設定跨來源存取 (CORS)。您可以使用 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 中的檔案中繼資料。