Как скачать файлы с помощью Cloud Storage в веб-интерфейсе

Cloud Storage for Firebase позволяет быстро и легко скачивать файлы из сегмента Cloud Storage, предоставленного Firebase и управляемого этим сервисом.

Создание ссылки

Чтобы скачать файл, сначала создайте ссылку Cloud Storage на него.

Вы можете создать ссылку, добавив дочерние пути к корню сегмента Cloud Storage, или создать ссылку из существующего URL-адреса 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');  

Скачивание данных по URL

Чтобы получить URL для скачивания файла, вызовите метод getDownloadURL() для ссылки Cloud Storage.

Web

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

const storage = getStorage();
const starsRef = ref(storage, 'images/stars.jpg');

getDownloadURL(starsRef)
  .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 предоставляет следующие функции для прямого скачивания:

С помощью этих функций вы можете не скачивать данные по URL, а возвращать их в коде. Это позволяет более точно управлять доступом с помощью 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 download
        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 download
      break;

    // ...

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

Вы также можете получать и обновлять метаданные файлов, хранящихся в Cloud Storage.