Utiliser des métadonnées de fichiers avec Cloud Storage sur le Web
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Après avoir importé un fichier dans la référence Cloud Storage, vous pouvez également obtenir ou mettre à jour les métadonnées du fichier, par exemple pour modifier le type de contenu. Les fichiers peuvent également stocker des paires clé/valeur personnalisées avec des métadonnées de fichier supplémentaires.
Obtenir les métadonnées d'un fichier
Les métadonnées de fichier contiennent des propriétés courantes telles que name, size et contentType (souvent appelé type MIME), en plus de propriétés moins courantes comme contentDisposition et timeCreated. Ces métadonnées peuvent être récupérées à partir d'une référence Cloud Storage à l'aide de la méthode getMetadata(). getMetadata() renvoie un Promise contenant les métadonnées complètes ou une erreur si le Promise est refusé.
Web
import{getStorage,ref,getMetadata}from"firebase/storage";// Create a reference to the file whose metadata we want to retrieveconststorage=getStorage();constforestRef=ref(storage,'images/forest.jpg');// Get metadata propertiesgetMetadata(forestRef).then((metadata)=>{// Metadata now contains the metadata for 'images/forest.jpg'}).catch((error)=>{// Uh-oh, an error occurred!});
// Create a reference to the file whose metadata we want to retrievevarforestRef=storageRef.child('images/forest.jpg');// Get metadata propertiesforestRef.getMetadata().then((metadata)=>{// Metadata now contains the metadata for 'images/forest.jpg'}).catch((error)=>{// Uh-oh, an error occurred!});
Vous pouvez mettre à jour les métadonnées d'un fichier à tout moment après l'importation à l'aide de la méthode updateMetadata(). Pour en savoir plus sur les propriétés pouvant être mises à jour, consultez la liste complète. Seules les propriétés spécifiées dans les métadonnées sont mises à jour. Toutes les autres restent inchangées. updateMetadata() renvoie un Promise contenant les métadonnées complètes ou une erreur si le Promise est refusé.
Web
import{getStorage,ref,updateMetadata}from"firebase/storage";// Create a reference to the file whose metadata we want to changeconststorage=getStorage();constforestRef=ref(storage,'images/forest.jpg');// Create file metadata to updateconstnewMetadata={cacheControl:'public,max-age=300',contentType:'image/jpeg'};// Update metadata propertiesupdateMetadata(forestRef,newMetadata).then((metadata)=>{// Updated metadata for 'images/forest.jpg' is returned in the Promise}).catch((error)=>{// Uh-oh, an error occurred!});
// Create a reference to the file whose metadata we want to changevarforestRef=storageRef.child('images/forest.jpg');// Create file metadata to updatevarnewMetadata={cacheControl:'public,max-age=300',contentType:'image/jpeg'};// Update metadata propertiesforestRef.updateMetadata(newMetadata).then((metadata)=>{// Updated metadata for 'images/forest.jpg' is returned in the Promise}).catch((error)=>{// Uh-oh, an error occurred!});
Vous pouvez supprimer une propriété de métadonnées en la définissant sur null :
Web
import{getStorage,ref,updateMetadata}from"firebase/storage";conststorage=getStorage();constforestRef=ref(storage,'images/forest.jpg');// Create file metadata with property to deleteconstdeleteMetadata={contentType:null};// Delete the metadata propertyupdateMetadata(forestRef,deleteMetadata).then((metadata)=>{// metadata.contentType should be null}).catch((error)=>{// Uh-oh, an error occurred!});
// Create file metadata with property to deletevardeleteMetadata={contentType:null};// Delete the metadata propertyforestRef.updateMetadata(deleteMetadata).then((metadata)=>{// metadata.contentType should be null}).catch((error)=>{// Uh-oh, an error occurred!});
Plusieurs raisons peuvent expliquer les erreurs lors de la récupération ou de la mise à jour des métadonnées, y compris l'inexistence du fichier ou l'absence d'autorisation de l'utilisateur pour accéder au fichier souhaité. Pour en savoir plus sur les erreurs, consultez la section Gérer les erreurs de la documentation.
Métadonnées personnalisées
Vous pouvez spécifier des métadonnées personnalisées sous la forme d'un objet contenant des propriétés String.
Web
constmetadata={customMetadata:{'location':'Yosemite, CA, USA','activity':'Hiking'}};
Vous pouvez utiliser des métadonnées personnalisées pour stocker des données supplémentaires spécifiques à l'application pour chaque fichier, mais nous vous recommandons vivement d'utiliser une base de données (telle que Firebase Realtime Database) pour stocker et synchroniser ce type de données.
Propriétés des métadonnées de fichier
Vous trouverez ci-dessous la liste complète des propriétés de métadonnées d'un fichier :
Propriété
Type
Accessible en écriture
bucket
chaîne
NON
generation
chaîne
NON
metageneration
chaîne
NON
fullPath
chaîne
NON
name
chaîne
NON
size
Total
NON
timeCreated
chaîne
NON
updated
chaîne
NON
md5Hash
chaîne
OUI pour l'importation, NON pour updateMetadata
cacheControl
chaîne
OUI
contentDisposition
chaîne
OUI
contentEncoding
chaîne
OUI
contentLanguage
chaîne
OUI
contentType
chaîne
OUI
customMetadata
Objet contenant des mappages chaîne->chaîne
OUI
Il est important de pouvoir importer, télécharger et modifier des fichiers, mais il est tout aussi important de pouvoir les supprimer. Découvrons comment supprimer des fichiers de Cloud Storage.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/08 (UTC).
[null,null,["Dernière mise à jour le 2025/08/08 (UTC)."],[],[],null,["\u003cbr /\u003e\n\nAfter uploading a file to Cloud Storage reference, you can also get\nor update the file metadata, for example to update the content type. Files\ncan also store custom key/value pairs with additional file metadata.\n| **Note:** By default, a Cloud Storage for Firebase bucket requires Firebase Authentication to perform any action on the bucket's data or files. You can change your Firebase Security Rules for Cloud Storage to [allow unauthenticated access for specific situations](/docs/storage/security/rules-conditions#public). However, for most situations, we strongly recommend [restricting access and setting up robust security rules](/docs/storage/security/get-started) (especially for production apps). Note that if you use Google App Engine and have a default Cloud Storage bucket with a name format of `*.appspot.com`, you may need to consider [how your security rules impact access to App Engine files](/docs/storage/gcp-integration#security-rules-and-app-engine-files).\n\nGet File Metadata\n\nFile metadata contains common properties such as `name`, `size`, and\n`contentType` (often referred to as MIME type) in addition to some less\ncommon ones like `contentDisposition` and `timeCreated`. This metadata can be\nretrieved from a Cloud Storage reference using\nthe `getMetadata()` method. `getMetadata()` returns a `Promise` containing the\ncomplete metadata, or an error if the `Promise` rejects. \n\nWeb \n\n```javascript\nimport { getStorage, ref, getMetadata } from \"firebase/storage\";\n\n// Create a reference to the file whose metadata we want to retrieve\nconst storage = getStorage();\nconst forestRef = ref(storage, 'images/forest.jpg');\n\n// Get metadata properties\ngetMetadata(forestRef)\n .then((metadata) =\u003e {\n // Metadata now contains the metadata for 'images/forest.jpg'\n })\n .catch((error) =\u003e {\n // Uh-oh, an error occurred!\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/storage-next/file-metadata/storage_get_metadata.js#L8-L21\n```\n\nWeb \n\n```javascript\n// Create a reference to the file whose metadata we want to retrieve\nvar forestRef = storageRef.child('images/forest.jpg');\n\n// Get metadata properties\nforestRef.getMetadata()\n .then((metadata) =\u003e {\n // Metadata now contains the metadata for 'images/forest.jpg'\n })\n .catch((error) =\u003e {\n // Uh-oh, an error occurred!\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/storage/file-metadata.js#L8-L18\n```\n\nUpdate File Metadata\n\nYou can update file metadata at any time after the file upload completes by\nusing the `updateMetadata()` method. Refer to the\n[full list](#file_metadata_properties) for more information on what properties\ncan be updated. Only the properties specified in the metadata are updated,\nall others are left unmodified. `updateMetadata()` returns a `Promise`\ncontaining the complete metadata, or an error if the `Promise` rejects. \n\nWeb \n\n```javascript\nimport { getStorage, ref, updateMetadata } from \"firebase/storage\";\n\n// Create a reference to the file whose metadata we want to change\nconst storage = getStorage();\nconst forestRef = ref(storage, 'images/forest.jpg');\n\n// Create file metadata to update\nconst newMetadata = {\n cacheControl: 'public,max-age=300',\n contentType: 'image/jpeg'\n};\n\n// Update metadata properties\nupdateMetadata(forestRef, newMetadata)\n .then((metadata) =\u003e {\n // Updated metadata for 'images/forest.jpg' is returned in the Promise\n }).catch((error) =\u003e {\n // Uh-oh, an error occurred!\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/storage-next/file-metadata/storage_update_metadata.js#L8-L26\n```\n\nWeb \n\n```javascript\n// Create a reference to the file whose metadata we want to change\nvar forestRef = storageRef.child('images/forest.jpg');\n\n// Create file metadata to update\nvar newMetadata = {\n cacheControl: 'public,max-age=300',\n contentType: 'image/jpeg'\n};\n\n// Update metadata properties\nforestRef.updateMetadata(newMetadata)\n .then((metadata) =\u003e {\n // Updated metadata for 'images/forest.jpg' is returned in the Promise\n }).catch((error) =\u003e {\n // Uh-oh, an error occurred!\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/storage/file-metadata.js#L26-L41\n```\n\nYou can delete a metadata property by setting it to `null`: \n\nWeb \n\n```javascript\nimport { getStorage, ref, updateMetadata } from \"firebase/storage\";\n\nconst storage = getStorage();\nconst forestRef = ref(storage, 'images/forest.jpg');\n\n// Create file metadata with property to delete\nconst deleteMetadata = {\n contentType: null\n};\n\n// Delete the metadata property\nupdateMetadata(forestRef, deleteMetadata)\n .then((metadata) =\u003e {\n // metadata.contentType should be null\n }).catch((error) =\u003e {\n // Uh-oh, an error occurred!\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/storage-next/file-metadata/storage_delete_metadata.js#L8-L24\n```\n\nWeb \n\n```javascript\n// Create file metadata with property to delete\nvar deleteMetadata = {\n contentType: null\n};\n\n// Delete the metadata property\nforestRef.updateMetadata(deleteMetadata)\n .then((metadata) =\u003e {\n // metadata.contentType should be null\n }).catch((error) =\u003e {\n // Uh-oh, an error occurred!\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/storage/file-metadata.js#L50-L62\n```\n\nHandle Errors\n\nThere are a number of reasons why errors may occur on getting or updating\nmetadata, including the file not existing, or the user not having permission\nto access the desired file. More information on errors can be found in the\n[Handle Errors](/docs/storage/web/handle-errors)\nsection of the docs.\n\nCustom Metadata\n\nYou can specify custom metadata as an object containing `String` properties. \n\nWeb \n\n```javascript\nconst metadata = {\n customMetadata: {\n 'location': 'Yosemite, CA, USA',\n 'activity': 'Hiking'\n }\n};https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/snippets/storage-next/file-metadata/storage_custom_metadata.js#L8-L13\n```\n\nWeb \n\n```javascript\nvar metadata = {\n customMetadata: {\n 'location': 'Yosemite, CA, USA',\n 'activity': 'Hiking'\n }\n};https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/storage/file-metadata.js#L68-L73\n```\n\nYou can use custom metadata for storing additional app specific data for each\nfile, but we highly recommend using a database (such as the\n[Firebase Realtime Database](/docs/database))\nto store and synchronize this type of data.\n\nFile Metadata Properties\n\nA full list of metadata properties on a file is available below:\n\n| Property | Type | Writable |\n|----------------------|--------------------------------------------|-------------------------------------|\n| `bucket` | string | NO |\n| `generation` | string | NO |\n| `metageneration` | string | NO |\n| `fullPath` | string | NO |\n| `name` | string | NO |\n| `size` | number | NO |\n| `timeCreated` | string | NO |\n| `updated` | string | NO |\n| `md5Hash` | string | YES on upload, NO on updateMetadata |\n| `cacheControl` | string | YES |\n| `contentDisposition` | string | YES |\n| `contentEncoding` | string | YES |\n| `contentLanguage` | string | YES |\n| `contentType` | string | YES |\n| `customMetadata` | Object containing string-\\\u003estring mappings | YES |\n\n| **Note:** at present, setting the `md5Hash` property on upload doesn't affect the upload, as hash verification is not yet implemented.\n\nUploading, downloading, and updating files is important, but so is being able\nto remove them. Let's learn how to\n[delete files](/docs/storage/web/delete-files)\nfrom Cloud Storage."]]