在将文件上传到 Cloud Storage 引用之后,您还可以获取和更新文件元数据,例如更新内容类型。文件还可以使用额外的文件元数据来存储自定义键值对。
获取文件元数据
文件元数据包含 name、size 和 content_type(通常称为 MIME 类型)等常用属性;以及 content_disposition 和 time_created 等不太常用的属性。您可以使用 GetMetadata 方法从 Cloud Storage 引用中检索此元数据。
// Create reference to the file whose metadata we want to retrieve StorageReference forest_ref = storage_ref.Child("images/forest.jpg"); // Get metadata properties Futurefuture = forest_ref.GetMetadata(); // Wait for Future to complete... if (future.Error() != firebase::storage::kErrorNone) { // Uh-oh, an error occurred! } else { // We can now retrieve the metadata for 'images/forest.jpg' Metadata* metadata = future.Result(); } 
更新文件元数据
文件上传完毕后,您可以使用 UpdateMetadata 方法随时更新文件元数据。请参考完整列表,详细了解哪些属性可以更新。只有元数据中指定的属性才会更新,所有其他属性不会被修改。
// Create reference to the file whose metadata we want to change firebase::storage::StorageReference forest_ref = storage_ref.child("images/forest.jpg"); // Create file metadata to update Metadata new_metadata; newMetadata.set_cache_control("public,max-age=300"); newMetadata.set_content_type("image/jpeg"); // Update metadata properties Futurefuture = forest_ref.UpdateMetadata(new_metadata); // Wait for Future to complete... if (future.Error() != firebase::storage::kErrorNone) { // Uh-oh, an error occurred! } else { // We can now retrieve the updated metadata for 'images/forest.jpg' Metadata* metadata = future.Result(); } 
您可以通过传递空字符串来删除可写元数据属性:
// Create file metadata with property to delete StorageMetadata new_metadata; new_metadata.set_content_type(""); // Delete the metadata property Futurefuture = forest_ref.UpdateMetadata(new_metadata); // Wait for Future to complete... if (future.Error() != 0) { // Uh-oh, an error occurred! } else { // metadata.content_type() should be an empty string Metadata* metadata = future.Result(); } 
处理错误
获取或更新元数据时,有很多原因会引发错误,包括文件不存在或者用户无权访问相关的文件。如需了解有关错误的详细信息,请参阅文档的处理错误部分。
自定义元数据
您可以将自定义元数据指定为包含 std::string 属性的 std::map。
std::map<std::string, std::string>* custom_metadata = metadata.custom_metadata(); custom_metadata->insert(std::make_pair("location", "Yosemite, CA, USA"); custom_metadata->insert(std::make_pair("activity", "Hiking");
您可以在自定义元数据中为每个文件存储特定于应用的数据,不过我们强烈建议您使用数据库(例如 Firebase Realtime Database)来存储和同步这种类型的数据。
文件元数据属性
文件元数据属性的完整列表如下:
| 属性 | 类型 | 是否可写入 | 
|---|---|---|
| bucket | const char* | 否 | 
| generation | const char* | 否 | 
| metageneration | const char* | 否 | 
| full_path | const char* | 否 | 
| name | const char* | 否 | 
| size | int64_t | 否 | 
| time_created | int64_t | 否 | 
| updated | int64_t | 否 | 
| cache_control | const char* | 是 | 
| content_disposition | const char* | 是 | 
| content_encoding | const char* | 是 | 
| content_language | const char* | 是 | 
| content_type | const char* | 是 | 
| download_urls | std::vector<std::string> | 否 | 
| custom_metadata | std::map<std::string, std::string> | 是 | 
后续步骤
上传、下载和更新文件很重要,但能够将其移除也同样重要。请了解如何从 Cloud Storage 中删除文件。