После загрузки файла в Cloud Storage вы также можете получить или обновить метаданные файла, например, чтобы обновить тип контента. Файлы также могут хранить пользовательские пары ключ/значение с дополнительными метаданными файла.
Получить метаданные файла
name
, size
и contentType
(часто называемые MIME-типом), а также некоторые менее распространенные свойства, такие как contentDisposition
и timeCreated
. Эти метаданные можно получить из ссылки на Cloud Storage с помощью метода getMetadata()
. getMetadata()
возвращает Promise
, содержащее полные метаданные, или ошибку, если Promise
отклоняется.
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! });
// 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! });
Обновить метаданные файла
updateMetadata()
. Обратитесь к полному списку для получения дополнительной информации о том, какие свойства можно обновить. Обновляются только свойства, указанные в метаданных, все остальные остаются неизмененными. updateMetadata()
возвращает Promise
, содержащее полные метаданные, или ошибку, если Promise
отклоняется.
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! });
// 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! });
null
:
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! });
// 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! });
Обработка ошибок
Пользовательские метаданные
String
.
const metadata = { customMetadata: { 'location': 'Yosemite, CA, USA', 'activity': 'Hiking' } };
var metadata = { customMetadata: { 'location': 'Yosemite, CA, USA', 'activity': 'Hiking' } };
Свойства метаданных файла
Свойство | Тип | записываемый |
---|---|---|
bucket | нить | НЕТ |
generation | нить | НЕТ |
metageneration | нить | НЕТ |
fullPath | нить | НЕТ |
name | нить | НЕТ |
size | число | НЕТ |
timeCreated | нить | НЕТ |
updated | нить | НЕТ |
md5Hash | нить | ДА при загрузке, НЕТ при обновлении метаданных |
cacheControl | нить | ДА |
contentDisposition | нить | ДА |
contentEncoding | нить | ДА |
contentLanguage | нить | ДА |
contentType | нить | ДА |
customMetadata | Объект, содержащий сопоставления строк->строки | ДА |