將檔案元資料與 Cloud Storage for C++ 結合使用

將檔案上傳到 Cloud Storage 參考後,您還可以獲得和更新檔案元數據,例如更新內容類型。文件還可以儲存自訂鍵/值對以及其他文件元資料。

取得文件元數據

檔案元資料包含常見屬性,例如namesizecontent_type (通常稱為 MIME 類型),以及一些不太常見的屬性(例如content_dispositiontime_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
Future future = 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
Future future = 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
Future future = 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* custom_metadata = metadata.custom_metadata();
custom_metadata->insert(std::make_pair("location", "Yosemite, CA, USA");
custom_metadata->insert(std::make_pair("activity", "Hiking");

您可以在自訂元資料中儲存每個檔案的應用特定數據,但我們強烈建議使用資料庫(例如Firebase 即時資料庫)來儲存和同步此類資料。

文件元資料屬性

下面提供了文件元資料屬性的完整清單:

財產類型可寫
bucket常數字元*
generation常數字元*
metageneration常數字元*
full_path常數字元*
name常數字元*
size int64_t
time_created int64_t
updated int64_t
cache_control常數字元*是的
content_disposition常數字元*是的
content_encoding常數字元*是的
content_language常數字元*是的
content_type常數字元*是的
download_urls std::向量<std::string>
custom_metadata std::map<std::string, std::string>是的

下一步

上傳、下載和更新檔案很重要,但刪除它們的能力也很重要。讓我們了解如何從雲端儲存中刪除檔案