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
Cree una referencia para cargar, descargar o eliminar un archivo, o para obtener o actualizar sus metadatos. Se puede pensar en una referencia como un puntero a un archivo en la nube. Las referencias son ligeras, por lo que puede crear tantas como necesite. También son reutilizables para múltiples operaciones.
Cree una referencia usando la instancia única de FirebaseStorage
y llamando a su método getReference()
.
Kotlin+KTX
// Create a storage reference from our app var storageRef = storage.reference
Java
// Create a storage reference from our app StorageReference storageRef = storage.getReference();
A continuación, puede crear una referencia a una ubicación más baja en el árbol, digamos "images/space.jpg"
usando el método child()
en una referencia existente.
Kotlin+KTX
// Create a child reference // imagesRef now points to "images" var imagesRef: StorageReference? = storageRef.child("images") // Child references can also take paths // spaceRef now points to "images/space.jpg // imagesRef still points to "images" var spaceRef = storageRef.child("images/space.jpg")
Java
// Create a child reference // imagesRef now points to "images" StorageReference imagesRef = storageRef.child("images"); // Child references can also take paths // spaceRef now points to "images/space.jpg // imagesRef still points to "images" StorageReference spaceRef = storageRef.child("images/space.jpg");
Navegar con Referencias
También puede usar los getParent()
y getRoot()
para navegar hacia arriba en nuestra jerarquía de archivos. getParent()
navega hacia arriba un nivel, mientras que getRoot()
navega hasta la parte superior.
Kotlin+KTX
// parent allows us to move our reference to a parent node // imagesRef now points to 'images' imagesRef = spaceRef.parent // root allows us to move all the way back to the top of our bucket // rootRef now points to the root val rootRef = spaceRef.root
Java
// getParent allows us to move our reference to a parent node // imagesRef now points to 'images' imagesRef = spaceRef.getParent(); // getRoot allows us to move all the way back to the top of our bucket // rootRef now points to the root StorageReference rootRef = spaceRef.getRoot();
child()
, getParent()
y getRoot()
se pueden encadenar varias veces, ya que cada uno devuelve una referencia. Pero llamar a getRoot().getParent()
devuelve null
.
Kotlin+KTX
// References can be chained together multiple times // earthRef points to 'images/earth.jpg' val earthRef = spaceRef.parent?.child("earth.jpg") // nullRef is null, since the parent of root is null val nullRef = spaceRef.root.parent
Java
// References can be chained together multiple times // earthRef points to 'images/earth.jpg' StorageReference earthRef = spaceRef.getParent().child("earth.jpg"); // nullRef is null, since the parent of root is null StorageReference nullRef = spaceRef.getRoot().getParent();
Propiedades de referencia
Puede inspeccionar las referencias para comprender mejor los archivos a los que apuntan mediante los getPath()
, getName()
y getBucket()
. Estos métodos obtienen la ruta completa, el nombre y el depósito del archivo.
Kotlin+KTX
// Reference's path is: "images/space.jpg" // This is analogous to a file path on disk spaceRef.path // 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 that the files are stored in spaceRef.bucket
Java
// Reference's path is: "images/space.jpg" // This is analogous to a file path on disk spaceRef.getPath(); // Reference's name is the last segment of the full path: "space.jpg" // This is analogous to the file name spaceRef.getName(); // Reference's bucket is the name of the storage bucket that the files are stored in spaceRef.getBucket();
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
Kotlin+KTX
// Points to the root reference storageRef = storage.reference // Points to "images" imagesRef = storageRef.child("images") // Points to "images/space.jpg" // Note that you can use variables to create child values val fileName = "space.jpg" spaceRef = imagesRef.child(fileName) // File path is "images/space.jpg" val path = spaceRef.path // File name is "space.jpg" val name = spaceRef.name // Points to "images" imagesRef = spaceRef.parent
Java
// Points to the root reference storageRef = storage.getReference(); // Points to "images" imagesRef = storageRef.child("images"); // Points to "images/space.jpg" // Note that you can use variables to create child values String fileName = "space.jpg"; spaceRef = imagesRef.child(fileName); // File path is "images/space.jpg" String path = spaceRef.getPath(); // File name is "space.jpg" String name = spaceRef.getName(); // Points to "images" imagesRef = spaceRef.getParent();
A continuación, aprendamos cómo cargar archivos en Cloud Storage.