使用 Web 上的 Cloud Storage 下載文件

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

建立參考

若要下載文件,請先建立要下載的文件的 Cloud Storage 引用

您可以透過將子路徑附加到 Cloud Storage 儲存桶的根來建立引用,也可以從引用 Cloud Storage 中物件的現有gs://https:// URL 建立參考。

Web modular API

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 namespaced API

// 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');  

透過 URL 下載數據

您可以透過對 Cloud Storage 引用呼叫getDownloadURL()方法來取得檔案的下載 URL。

Web modular API

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 namespaced API

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提供了以下函數供直接下載:

使用這些函數,您可以繞過從 URL 下載,而是在程式碼中傳回資料。這允許透過Firebase 安全規則進行更細粒度的存取控制。

CORS配置

若要直接在瀏覽器中下載數據,您必須將 Cloud Storage 儲存分區配置為跨來源存取 (CORS)。這可以使用gsutil命令列工具來完成,您可以從此處安裝該工具。

如果您不需要任何基於網域的限制(最常見的情況),請將此 JSON 複製到名為cors.json的檔案:

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

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

有關更多信息,請參閱Google 雲端儲存文件

處理錯誤

下載時出現錯誤的原因有很多,包括文件不存在或使用者沒有存取所需文件的權限。有關錯誤的更多資訊可以在文件的處理錯誤部分找到。

完整範例

下面顯示了帶有錯誤處理的下載的完整範例:

Web modular API

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 namespaced API

// 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 中的檔案的元資料