Menggunakan metadata file dengan Cloud Storage di Web
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Setelah mengupload file ke referensi Cloud Storage, Anda juga dapat mengambil atau memperbarui metadata file, misalnya untuk memperbarui jenis konten. File juga dapat menyimpan key-value pair kustom dengan metadata file tambahan.
Mengambil Metadata File
Metadata file berisi properti umum, seperti name, size, dan contentType (sering disebut jenis MIME), serta beberapa properti yang jarang digunakan, seperti contentDisposition dan timeCreated. Metadata ini dapat diambil dari referensi Cloud Storage menggunakan metode getMetadata(). getMetadata() menampilkan Promise
yang berisi metadata lengkap, atau error jika Promise menolak.
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!});
Anda dapat memperbarui metadata file kapan saja setelah file selesai diupload menggunakan metode updateMetadata(). Lihat daftar lengkap untuk mengetahui informasi lebih lanjut mengenai properti yang dapat diperbarui. Hanya properti yang ditetapkan dalam metadata yang akan diperbarui,
sedangkan yang lainnya tidak berubah. updateMetadata() menampilkan Promise
yang berisi metadata lengkap, atau error jika Promise menolak.
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!});
Anda dapat menghapus properti metadata dengan menyetelnya ke 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!});
Ada sejumlah alasan terjadinya error saat mengambil atau memperbarui metadata, termasuk tidak adanya file atau pengguna tidak memiliki izin untuk mengakses file yang diinginkan. Informasi lebih lanjut mengenai error bisa dilihat di bagian Menangani Error pada dokumentasi.
Metadata Kustom
Anda dapat menentukan metadata kustom sebagai objek yang berisi properti String.
Web
constmetadata={customMetadata:{'location':'Yosemite, CA, USA','activity':'Hiking'}};
Anda dapat menggunakan metadata kustom untuk menyimpan data khusus aplikasi tambahan untuk setiap file, tetapi kami sangat menyarankan untuk menggunakan database (seperti
Firebase Realtime Database)
untuk menyimpan dan menyinkronkan jenis data ini.
Properti Metadata File
Daftar lengkap properti metadata pada file tercantum di bawah ini:
Properti
Jenis
Dapat Ditulis
bucket
string
TIDAK
generation
string
TIDAK
metageneration
string
TIDAK
fullPath
string
TIDAK
name
string
TIDAK
size
angka
TIDAK
timeCreated
string
TIDAK
updated
string
TIDAK
md5Hash
string
YA untuk upload, TIDAK untuk updateMetadata
cacheControl
string
YA
contentDisposition
string
YA
contentEncoding
string
YA
contentLanguage
string
YA
contentType
string
YA
customMetadata
Objek yang berisi string->pemetaan string
YA
Mengupload, mendownload, dan memperbarui file itu penting, tetapi kita juga harus bisa menghapusnya. Mari pelajari cara menghapus file dari Cloud Storage.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Informasi yang saya butuhkan tidak ada","missingTheInformationINeed","thumb-down"],["Terlalu rumit/langkahnya terlalu banyak","tooComplicatedTooManySteps","thumb-down"],["Sudah usang","outOfDate","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Masalah kode / contoh","samplesCodeIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-08-14 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."]]