通过 Flutter 上的 Cloud Storage 使用文件元数据

在将文件上传到 Cloud Storage 引用之后,您还可以获取和更新文件元数据,例如查看或更新内容类型。文件还可以使用额外的文件元数据来存储自定义键值对。

获取文件元数据

文件元数据包含 namesizecontentType(通常称为 MIME 类型)等常用属性,以及 contentDispositiontimeCreated 等不太常用的属性。您可以使用 getMetadata() 方法从 Cloud Storage 引用中检索此元数据。

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

// Get metadata properties
final metadata = await forestRef.getMetadata();

// Metadata now contains the metadata for 'images/forest.jpg'

更新文件元数据

文件上传完毕后,您可以使用 updateMetadata() 方法随时更新文件元数据。请参考完整列表,详细了解哪些属性可以更新。只有元数据中指定的属性才会更新,所有其他属性均不会被修改。

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

// Create file metadata to update
final newMetadata = SettableMetadata(
  cacheControl: "public,max-age=300",
  contentType: "image/jpeg",
);

// Update metadata properties
final metadata = await forestRef.updateMetadata(newMetadata);

// Updated metadata for 'images/forest.jpg' is returned

对于可写元数据属性,您可以通过传递 null 来将其删除:

// Delete the cacheControl property
final newMetadata = SettableMetadata(cacheControl: null);
final metadata = await forestRef.updateMetadata(newMetadata);

处理错误

获取或更新元数据时,有很多原因会引发错误,包括文件不存在或者用户无权访问相关的文件。如需详细了解这些错误,请参阅文档的处理错误部分。

自定义元数据

您可以使用 SettableMetadata 构造函数的 customMetadata 参数指定自定义元数据:

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

// Create file metadata to update
final newCustomMetadata = SettableMetadata(
  customMetadata: {
    "location": "Yosemite, CA, USA",
    "activity": "Hiking",
  },
);

// Update metadata properties
final metadata = await forestRef.updateMetadata(newCustomMetadata);

// Updated metadata for 'images/forest.jpg' is returned

您可以在自定义元数据中为每个文件存储应用专属的数据,不过我们强烈建议您使用数据库(例如 Firebase Realtime Database)来存储和同步这种类型的数据。

文件元数据属性

文件元数据属性的完整列表如下:

属性 类型 是否可以设置?
bucket String
generation String 不具备
metageneration String 不具备
metadataGeneration String 不具备
fullPath String 不具备
name String 不具备
size int 不具备
timeCreated DateTime 不具备
updated DateTime 不具备
md5Hash String
cacheControl String
contentDisposition String
contentEncoding String
contentLanguage String
contentType String
customMetadata Map<String, String>

上传、下载和更新文件很重要,但能够将文件移除也同样重要。请了解如何从 Cloud Storage 中删除文件