Sus archivos se almacenan en un depósito de Cloud Storage . Los archivos en este depósito se presentan en una estructura jerárquica, al igual que el sistema de archivos en su disco duro local o los datos en Firebase Realtime Database. Al crear una referencia a un archivo, su aplicación obtiene acceso a él. Estas referencias se pueden usar para cargar o descargar datos, obtener o actualizar metadatos o eliminar el archivo. Una referencia puede apuntar a un archivo específico o a un nodo de nivel superior en la jerarquía.
Si ha utilizado Firebase Realtime Database , estas rutas le resultarán muy familiares. Sin embargo, los datos de su archivo se almacenan en Cloud Storage, no en Realtime Database.
Crear una referencia
Para cargar o descargar archivos, eliminar archivos u obtener o actualizar metadatos, debe crear una referencia al archivo en el que desea operar. Se puede pensar en una referencia como un puntero a un archivo en la nube. Las referencias son livianas, por lo que puede crear tantas como necesite, y también son reutilizables para múltiples operaciones.
Para crear una referencia, obtenga una instancia del servicio de almacenamiento usando getStorage()
y luego llame a ref()
con el servicio como argumento. Esta referencia apunta a la raíz de su depósito de Cloud Storage.
Web version 9
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);
Web version 8
// 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();
Puede crear una referencia a una ubicación más baja en el árbol, digamos 'images/space.jpg'
al pasar esta ruta como un segundo argumento al llamar a ref()
.
Web version 9
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"
Web version 8
// 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"
Navegar con Referencias
También puede usar las propiedades parent
y root
para navegar hacia arriba en la jerarquía de archivos. parent
sube un nivel, mientras que root
navega hasta el final.
Web version 9
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
Web version 8
// 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 encadenar varias veces, ya que cada uno devuelve una referencia. La excepción es el parent
de root
, que es null
.
Web version 9
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;
Web version 8
// 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 referencia
Puede inspeccionar las referencias para comprender mejor los archivos a los que apuntan utilizando las fullPath
, name
y bucket
. Estas propiedades obtienen la ruta completa del archivo, el nombre del archivo y el depósito en el que se almacena el archivo.
Web version 9
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;
Web version 8
// 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 en las Referencias
Las rutas de referencia y los nombres pueden contener cualquier secuencia de caracteres Unicode válidos, pero se imponen ciertas restricciones, que incluyen:
- La longitud total de
reference.fullPath
debe estar entre 1 y 1024 bytes cuando se codifica en UTF-8. - Sin caracteres de retorno de carro o avance de línea.
- Evite usar
#
,[
,]
,*
o?
, ya que no funcionan bien con otras herramientas como Firebase Realtime Database o gsutil .
Ejemplo completo
Web version 9
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;
Web version 8
// 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, aprendamos cómo cargar archivos en Cloud Storage.