使用 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 中的檔案