Utilizzare i metadati dei file con Cloud Storage su Android

Dopo aver caricato un file nel riferimento Cloud Storage, puoi anche recuperare e aggiornare i metadati del file, ad esempio per visualizzare o aggiornare il tipo di contenuto. I file possono anche archiviare coppie chiave/valore personalizzate con metadati aggiuntivi.

Recupera metadati file

I metadati dei file contengono proprietà comuni come name, size e contentType (spesso indicato come tipo MIME), oltre ad alcune meno comuni come contentDisposition e timeCreated. Questi metadati possono essere recuperati da un riferimento Cloud Storage utilizzando il metodo getMetadata().

Kotlin

// Create a storage reference from our app
val storageRef = storage.reference

// Get reference to the file
val forestRef = storageRef.child("images/forest.jpg")
forestRef.metadata.addOnSuccessListener { metadata ->
    // Metadata now contains the metadata for 'images/forest.jpg'
}.addOnFailureListener {
    // Uh-oh, an error occurred!
}

Java

// Create a storage reference from our app
StorageReference storageRef = storage.getReference();

// Get reference to the file
StorageReference forestRef = storageRef.child("images/forest.jpg");
forestRef.getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
    @Override
    public void onSuccess(StorageMetadata storageMetadata) {
        // Metadata now contains the metadata for 'images/forest.jpg'
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Uh-oh, an error occurred!
    }
});

Aggiornare i metadati del file

Puoi aggiornare i metadati del file in qualsiasi momento dopo il completamento del caricamento utilizzando il metodo updateMetadata(). Per ulteriori informazioni sulle proprietà che possono essere aggiornate, consulta l'elenco completo. Vengono aggiornate solo le proprietà specificate nei metadati, tutte le altre rimangono invariate.

Kotlin

// Create a storage reference from our app
val storageRef = storage.reference

// Get reference to the file
val forestRef = storageRef.child("images/forest.jpg")
// Create file metadata including the content type
val metadata = storageMetadata {
    contentType = "image/jpg"
    setCustomMetadata("myCustomProperty", "myValue")
}

// Update metadata properties
forestRef.updateMetadata(metadata).addOnSuccessListener { updatedMetadata ->
    // Updated metadata is in updatedMetadata
}.addOnFailureListener {
    // Uh-oh, an error occurred!
}

Java

// Create a storage reference from our app
StorageReference storageRef = storage.getReference();

// Get reference to the file
StorageReference forestRef = storageRef.child("images/forest.jpg");
// Create file metadata including the content type
StorageMetadata metadata = new StorageMetadata.Builder()
        .setContentType("image/jpg")
        .setCustomMetadata("myCustomProperty", "myValue")
        .build();

// Update metadata properties
forestRef.updateMetadata(metadata)
        .addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
            @Override
            public void onSuccess(StorageMetadata storageMetadata) {
                // Updated metadata is in storageMetadata
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Uh-oh, an error occurred!
            }
        });

Puoi eliminare le proprietà dei metadati scrivibili passando null:

Kotlin

// Create file metadata with property to delete
val metadata = storageMetadata {
    contentType = null
}

// Delete the metadata property
forestRef.updateMetadata(metadata).addOnSuccessListener { updatedMetadata ->
    // updatedMetadata.contentType should be null
}.addOnFailureListener {
    // Uh-oh, an error occurred!
}

Java

// Create file metadata with property to delete
StorageMetadata metadata = new StorageMetadata.Builder()
        .setContentType(null)
        .build();

// Delete the metadata property
forestRef.updateMetadata(metadata)
        .addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
            @Override
            public void onSuccess(StorageMetadata storageMetadata) {
                // metadata.contentType should be null
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Uh-oh, an error occurred!
            }
        });

Gestisci gli errori

Esistono diversi motivi per cui potrebbero verificarsi errori durante il recupero o l'aggiornamento dei metadati, tra cui l'inesistenza del file o la mancanza di autorizzazione dell'utente per accedere al file desiderato. Per ulteriori informazioni sugli errori, consulta la sezione Gestire gli errori della documentazione.

Metadati personalizzati

Puoi specificare metadati personalizzati utilizzando il metodo setCustomMetadata() nella classe StorageMetadata.Builder.

Kotlin

val metadata = storageMetadata {
    setCustomMetadata("location", "Yosemite, CA, USA")
    setCustomMetadata("activity", "Hiking")
}

Java

StorageMetadata metadata = new StorageMetadata.Builder()
        .setCustomMetadata("location", "Yosemite, CA, USA")
        .setCustomMetadata("activity", "Hiking")
        .build();

Puoi memorizzare dati specifici dell'app per ogni file nei metadati personalizzati, ma ti consigliamo vivamente di utilizzare un database (ad esempio Firebase Realtime Database) per memorizzare e sincronizzare questo tipo di dati.

Proprietà dei metadati del file

Di seguito è riportato un elenco completo delle proprietà dei metadati di un file:

Property Getter Tipo Setter Exists
getBucket String NO
getGeneration String NO
getMetadataGeneration String NO
getPath String NO
getName String NO
getSizeBytes long NO
getCreationTimeMillis long NO
getUpdatedTimeMillis long NO
getMd5Hash String NO
getCacheControl String
getContentDisposition String
getContentEncoding String
getContentLanguage String
getContentType String
getCustomMetadata String
getCustomMetadataKeys Set<String> NO

Il caricamento, il download e l'aggiornamento dei file sono importanti, ma lo è anche la possibilità di rimuoverli. Scopriamo come eliminare i file da Cloud Storage.