Crie uma referência do Cloud Storage no Android

Seus arquivos são armazenados em um bucket do Cloud Storage . Os arquivos neste bucket são apresentados em uma estrutura hierárquica, assim como o sistema de arquivos no disco rígido local ou os dados no Firebase Realtime Database. Ao criar uma referência a um arquivo, seu aplicativo ganha acesso a ele. Essas referências podem então ser usadas para fazer upload ou download de dados, obter ou atualizar metadados ou excluir o arquivo. Uma referência pode apontar para um arquivo específico ou para um nó de nível superior na hierarquia.

Se você usou o Firebase Realtime Database , esses caminhos devem parecer muito familiares para você. No entanto, os dados do seu arquivo são armazenados no Cloud Storage, e não no Realtime Database.

Crie uma referência

Crie uma referência para fazer upload, download ou excluir um arquivo ou para obter ou atualizar seus metadados. Uma referência pode ser considerada um ponteiro para um arquivo na nuvem. As referências são leves, então você pode criar quantas precisar. Eles também são reutilizáveis ​​para múltiplas operações.

Crie uma referência usando a instância singleton FirebaseStorage e chamando seu 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();

Em seguida, você pode criar uma referência para um local inferior na árvore, digamos "images/space.jpg" usando o método child() em uma referência 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");

Você também pode usar os métodos getParent() e getRoot() para navegar para cima em nossa hierarquia de arquivos. getParent() navega um nível acima, enquanto getRoot() navega até o topo.

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() e getRoot() podem ser encadeados várias vezes, pois cada um retorna uma referência. Mas chamar getRoot().getParent() retorna 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();

Propriedades de referência

Você pode inspecionar as referências para entender melhor os arquivos para os quais elas apontam usando os métodos getPath() , getName() e getBucket() . Esses métodos obtêm o caminho completo, o nome e o intervalo do arquivo.

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();

Limitações nas referências

Os caminhos e nomes de referência podem conter qualquer sequência de caracteres Unicode válidos, mas certas restrições são impostas, incluindo:

  1. O comprimento total de reference.fullPath deve estar entre 1 e 1.024 bytes quando codificado em UTF-8.
  2. Nenhum caractere de retorno de carro ou alimentação de linha.
  3. Evite usar # , [ , ] , * ou ? , pois não funcionam bem com outras ferramentas, como Firebase Realtime Database ou gsutil .

Exemplo 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 seguir, vamos aprender como fazer upload de arquivos para o Cloud Storage.