Utilizzare i metadati dei file con Cloud Storage sul web

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

Recupera i metadati del file

I metadati dei file contengono proprietà comuni come name, size e contentType (spesso definito 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(). getMetadata() restituisce un Promise contenente i metadati completi o un errore se il Promise viene rifiutato.

Web

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

// Create a reference to the file whose metadata we want to retrieve
const storage = getStorage();
const forestRef = ref(storage, 'images/forest.jpg');

// Get metadata properties
getMetadata(forestRef)
  .then((metadata) => {
    // Metadata now contains the metadata for 'images/forest.jpg'
  })
  .catch((error) => {
    // Uh-oh, an error occurred!
  });

Web

// Create a reference to the file whose metadata we want to retrieve
var forestRef = storageRef.child('images/forest.jpg');

// Get metadata properties
forestRef.getMetadata()
  .then((metadata) => {
    // Metadata now contains the metadata for 'images/forest.jpg'
  })
  .catch((error) => {
    // Uh-oh, an error occurred!
  });

Aggiorna i metadati del file

Puoi aggiornare i metadati del file in qualsiasi momento dopo il completamento del caricamento del file 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, mentre tutte le altre rimangono invariate. updateMetadata() restituisce un Promise contenente i metadati completi o un errore se Promise rifiuta.

Web

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

// Create a reference to the file whose metadata we want to change
const storage = getStorage();
const forestRef = ref(storage, 'images/forest.jpg');

// Create file metadata to update
const newMetadata = {
  cacheControl: 'public,max-age=300',
  contentType: 'image/jpeg'
};

// Update metadata properties
updateMetadata(forestRef, newMetadata)
  .then((metadata) => {
    // Updated metadata for 'images/forest.jpg' is returned in the Promise
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });

Web

// Create a reference to the file whose metadata we want to change
var forestRef = storageRef.child('images/forest.jpg');

// Create file metadata to update
var newMetadata = {
  cacheControl: 'public,max-age=300',
  contentType: 'image/jpeg'
};

// Update metadata properties
forestRef.updateMetadata(newMetadata)
  .then((metadata) => {
    // Updated metadata for 'images/forest.jpg' is returned in the Promise
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });

Puoi eliminare una proprietà dei metadati impostandola su null:

Web

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

const storage = getStorage();
const forestRef = ref(storage, 'images/forest.jpg');

// Create file metadata with property to delete
const deleteMetadata = {
  contentType: null
};

// Delete the metadata property
updateMetadata(forestRef, deleteMetadata)
  .then((metadata) => {
    // metadata.contentType should be null
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });

Web

// Create file metadata with property to delete
var deleteMetadata = {
  contentType: null
};

// Delete the metadata property
forestRef.updateMetadata(deleteMetadata)
  .then((metadata) => {
    // metadata.contentType should be null
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });

Gestisci gli errori

Esistono diversi motivi per cui possono verificarsi errori durante il recupero o l'aggiornamento dei metadati, ad esempio il file non esiste o l'utente non dispone dell'autorizzazione per accedere al file desiderato. Puoi trovare maggiori informazioni sugli errori nella sezione Gestisci gli errori della documentazione.

Metadati personalizzati

Puoi specificare i metadati personalizzati come un oggetto contenente proprietà String.

Web

const metadata = {
  customMetadata: {
    'location': 'Yosemite, CA, USA',
    'activity': 'Hiking'
  }
};

Web

var metadata = {
  customMetadata: {
    'location': 'Yosemite, CA, USA',
    'activity': 'Hiking'
  }
};

Puoi utilizzare i metadati personalizzati per archiviare dati aggiuntivi specifici dell'app per ogni file, ma ti consigliamo vivamente di utilizzare un database (come Firebase Realtime Database) per archiviare e sincronizzare questo tipo di dati.

Proprietà dei metadati dei file

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

Proprietà Tipo Scrivibile
bucket stringa NO
generation stringa NO
metageneration stringa NO
fullPath stringa NO
name stringa NO
size numero NO
timeCreated stringa NO
updated stringa NO
md5Hash stringa SÌ per il caricamento, NO per updateMetadata
cacheControl stringa SÌ
contentDisposition stringa SÌ
contentEncoding stringa SÌ
contentLanguage stringa SÌ
contentType stringa SÌ
customMetadata Oggetto contenente mappature stringa->stringa SÌ

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