Crea una referencia de Cloud Storage en la Web

Tus archivos se almacenan en un bucket de Cloud Storage. Los archivos que se encuentran en este bucket se presentan en una estructura jerárquica, al igual que el sistema de archivos de tu disco duro local o los datos de Firebase Realtime Database. Cuando creas una referencia a un archivo, tu app obtiene acceso a él. Estas referencias se pueden usar para subir o descargar datos, obtener o actualizar metadatos, o borrar el archivo. Una referencia puede apuntar a un archivo específico o a un nodo de nivel superior de la jerarquía.

Si usaste Firebase Realtime Database, seguramente ya conoces estas rutas. Sin embargo, los datos de tus archivos se almacenan en Cloud Storage, no en Realtime Database.

Crea una referencia

Para subir o descargar archivos, borrar archivos, obtener o actualizar metadatos, debes crear una referencia al archivo con el que deseas trabajar. Se puede decir que una referencia es un indicador que apunta a un archivo en la nube. Las referencias son livianas, por lo que puedes crear todas las que necesites, y también son reutilizables para múltiples operaciones.

Para crear una referencia, obtén una instancia del servicio de Storage mediante getStorage() y, luego, llama a ref() con el servicio como argumento. Esta referencia apunta a la raíz del bucket de Cloud Storage.

API modular web

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

// Get a reference to the storage service, which is used to create references in your storage bucket
const storage = getStorage();

// Create a storage reference from our storage service
const storageRef = ref(storage);

API con espacio de nombres web

// Get a reference to the storage service, which is used to create references in your storage bucket
var storage = firebase.storage();

// Create a storage reference from our storage service
var storageRef = storage.ref();

Puedes crear una referencia a una ubicación de un nivel inferior del árbol, como 'images/space.jpg', pasando esta ruta de acceso como un segundo argumento cuando llamas a ref().

API modular web

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

const storage = getStorage();

// Create a child reference
const imagesRef = ref(storage, 'images');
// imagesRef now points to 'images'

// Child references can also take paths delimited by '/'
const spaceRef = ref(storage, 'images/space.jpg');
// spaceRef now points to "images/space.jpg"
// imagesRef still points to "images"

API con espacio de nombres web

// Create a child reference
var imagesRef = storageRef.child('images');
// imagesRef now points to 'images'

// Child references can also take paths delimited by '/'
var spaceRef = storageRef.child('images/space.jpg');
// spaceRef now points to "images/space.jpg"
// imagesRef still points to "images"

También puedes usar las propiedades parent y root para navegar por la jerarquía de archivos. parent te permite subir un nivel y root te permite ir al nivel más alto.

API modular web

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

const storage = getStorage();
const spaceRef = ref(storage, 'images/space.jpg');

// Parent allows us to move to the parent of a reference
const imagesRef = spaceRef.parent;
// imagesRef now points to 'images'

// Root allows us to move all the way back to the top of our bucket
const rootRef = spaceRef.root;
// rootRef now points to the root

API con espacio de nombres web

// Parent allows us to move to the parent of a reference
var imagesRef = spaceRef.parent;
// imagesRef now points to 'images'

// Root allows us to move all the way back to the top of our bucket
var rootRef = spaceRef.root;
// rootRef now points to the root

child(), parent y root se pueden articular en conjunto varias veces, ya que cada uno muestra una referencia. La excepción es el parent de root, que es null.

API modular web

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

const storage = getStorage();
const spaceRef = ref(storage, 'images/space.jpg');

// References can be chained together multiple times
const earthRef = ref(spaceRef.parent, 'earth.jpg');
// earthRef points to 'images/earth.jpg'

// nullRef is null, since the parent of root is null
const nullRef = spaceRef.root.parent;

API con espacio de nombres web

// References can be chained together multiple times
var earthRef = spaceRef.parent.child('earth.jpg');
// earthRef points to 'images/earth.jpg'

// nullRef is null, since the parent of root is null
var nullRef = spaceRef.root.parent;

Propiedades de las referencias

Para revisar las referencias y comprender mejor los archivos a los que dirigen, puedes usar las propiedades fullPath, name y bucket. Estas propiedades permiten obtener la ruta de acceso completa del archivo, el nombre del archivo y el bucket en que está almacenado.

API modular web

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

const storage = getStorage();
const spaceRef = ref(storage, 'images/space.jpg');

// Reference's path is: 'images/space.jpg'
// This is analogous to a file path on disk
spaceRef.fullPath;

// Reference's name is the last segment of the full path: 'space.jpg'
// This is analogous to the file name
spaceRef.name;

// Reference's bucket is the name of the storage bucket where files are stored
spaceRef.bucket;

API con espacio de nombres web

// Reference's path is: 'images/space.jpg'
// This is analogous to a file path on disk
spaceRef.fullPath;

// Reference's name is the last segment of the full path: 'space.jpg'
// This is analogous to the file name
spaceRef.name;

// Reference's bucket is the name of the storage bucket where files are stored
spaceRef.bucket;

Limitaciones de las referencias

Las rutas de acceso y los nombres de las referencias pueden contener cualquier secuencia de caracteres Unicode válidos, pero se aplican algunas restricciones, como las siguientes:

  1. La longitud total de reference.fullPath debe ser de entre 1 y 1,024 bytes con codificación UTF-8.
  2. No se permiten los caracteres de retorno de carro ni de salto de línea.
  3. No uses #, [, ], * ni ?, ya que no funcionan correctamente con otras herramientas, como Firebase Realtime Database o gsutil.

Ejemplo completo

API modular web

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

const storage = getStorage();

// Points to the root reference
const storageRef = ref(storage);

// Points to 'images'
const imagesRef = ref(storageRef, 'images');

// Points to 'images/space.jpg'
// Note that you can use variables to create child values
const fileName = 'space.jpg';
const spaceRef = ref(imagesRef, fileName);

// File path is 'images/space.jpg'
const path = spaceRef.fullPath;

// File name is 'space.jpg'
const name = spaceRef.name;

// Points to 'images'
const imagesRefAgain = spaceRef.parent;

API con espacio de nombres web

// Points to the root reference
var storageRef = firebase.storage().ref();

// Points to 'images'
var imagesRef = storageRef.child('images');

// Points to 'images/space.jpg'
// Note that you can use variables to create child values
var fileName = 'space.jpg';
var spaceRef = imagesRef.child(fileName);

// File path is 'images/space.jpg'
var path = spaceRef.fullPath;

// File name is 'space.jpg'
var name = spaceRef.name;

// Points to 'images'
var imagesRef = spaceRef.parent;

A continuación, veamos cómo subir archivos a Cloud Storage.