透過 Flutter 上的 Cloud Storage 使用檔案中繼資料

將檔案上傳至 Cloud Storage 參考資料後,也能取得下列權限: 並更新檔案中繼資料,例如查看或更新內容類型。 檔案也能儲存自訂鍵/值組合與其他檔案中繼資料。

取得檔案中繼資料

檔案中繼資料包含常用屬性,例如 namesizecontentType (通常稱為 MIME 類型) contentDispositiontimeCreated 等常用屬性。中繼資料可以是 從 Cloud Storage 參考資料中擷取 getMetadata() 方法。

// 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);

處理錯誤

發生錯誤的可能原因有很多, 中繼資料,包括不存在的檔案,或使用者沒有權限 來存取所需檔案如要進一步瞭解錯誤,請前往 請參閱本文件的「處理錯誤」一節。

自訂中繼資料

您可以使用customMetadata SettableMetadata 建構函式:

// 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 即時資料庫),儲存並同步處理這種類型的 資料。

檔案中繼資料屬性

完整的檔案中繼資料屬性清單請見下方:

屬性 類型 是否可準備?
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 執行