透過 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 即時資料庫) 儲存及同步處理這類資料。

檔案中繼資料屬性

檔案的中繼資料屬性完整清單如下:

屬性 類型 可設定?
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 中的檔案