Descarga archivos con Cloud Storage en la Web

Cloud Storage para Firebase te permite descargar archivos con rapidez y facilidad desde un bucket de Cloud Storage proporcionado y administrado por Firebase.

Crea una referencia

Para descargar un archivo, primero crea una referencia de Cloud Storage al archivo que deseas descargar.

Para ello, puedes anexar rutas de acceso secundarias a la raíz de tu bucket de Cloud Storage o puedes crear una referencia a partir de una URL gs:// o https:// existente que haga referencia a un objeto en Cloud Storage.

API modular 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');  

API con espacio de nombres 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');  

Descarga datos a través de URL

Para obtener la URL de descarga de un archivo, puedes llamar al método getDownloadURL() en una referencia de Cloud Storage.

API modular 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
  });

API con espacio de nombres 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
  });

Descarga datos directamente desde el SDK

A partir de la versión 9.5 y las posteriores, el SDK proporciona las siguientes funciones para la descarga directa:

Con estas funciones, puedes omitir la descarga desde una URL y, en su lugar, mostrar datos en tu código. Esto ofrece un control de acceso más detallado a través de las reglas de seguridad de Firebase.

Configuración de CORS

Para descargar datos directamente en el navegador, debes configurar el bucket de Cloud Storage para el acceso multiorigen (CORS). Puedes hacerlo con la herramienta de línea de comandos gsutil, que puedes instalar desde aquí.

Si no deseas que se apliquen restricciones según el dominio (el caso más común), copia este código JSON a un archivo llamado cors.json:

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

Ejecuta gsutil cors set cors.json gs://<your-cloud-storage-bucket> para implementar estas restricciones.

Para obtener más información, consulta la documentación de Google Cloud Storage.

Soluciona errores

Existen varios motivos por los cuales se pueden producir errores en una descarga: por ejemplo, es posible que el archivo no exista o que el usuario no tenga permiso para acceder al archivo deseado. Para obtener más información sobre los errores, consulta la sección de los documentos denominada Soluciona errores.

Ejemplo completo

A continuación, se muestra un ejemplo completo de una descarga con manejo de errores:

API modular 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;
    }
  });

API con espacio de nombres 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;
  }
});

También puedes obtener o actualizar metadatos de los archivos almacenados en Cloud Storage.