Utilizzare i metadati dei file con Cloud Storage sul web

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

Recupera i metadati del 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 recuperata da un riferimento Cloud Storage utilizzando il metodo getMetadata(). getMetadata() restituisce un Promise contenente i metadati completi o un errore se 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 metadati file

Puoi aggiornare i metadati dei file in qualsiasi momento dopo il completamento del caricamento del file entro il usando il metodo updateMetadata(). Consulta l'elenco completo per ulteriori informazioni sulle proprietà che possono essere aggiornate. Vengono aggiornate solo le proprietà specificate nei metadati. tutte le altre non vengono modificate. 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!
  });

Gestire gli errori

Esistono diversi motivi per cui potrebbero verificarsi errori durante il recupero o l'aggiornamento metadati, inclusi quelli che non esistono o che l'utente non dispone dell'autorizzazione per accedere al file desiderato. Per ulteriori informazioni sugli errori, consulta il Gestire gli errori sezione dei documenti.

Metadati personalizzati

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

Web

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

Web

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

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

Proprietà metadati 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Ì al caricamento, NO su updateMetadata
cacheControl stringa
contentDisposition stringa
contentEncoding stringa
contentLanguage stringa
contentType stringa
customMetadata Oggetto contenente mappature stringa->stringa

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