从 Cloud Storage 下载文件 (Web)

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 中的文件,您还可以获取或更新元数据