透過適用於 C++ 的 Cloud Storage 使用檔案中繼資料

將檔案上傳至 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::stringstd::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 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 執行