搭配 Unity 專用 Cloud Storage 使用檔案中繼資料

將檔案上傳至 Cloud Storage 參考檔案後,您也可以取得及更新檔案中繼資料,例如更新內容類型。檔案也可以儲存自訂鍵/值組合,以及其他檔案中繼資料。

取得檔案中繼資料

檔案中繼資料包含 Name、SizeBytes 和 ContentType (通常稱為 MIME 類型) 等常見屬性,以及 ContentDisposition 和 CreationTimeMillis 等較不常見的屬性。您可以使用 GetMetadataAsync 方法,從 Cloud Storage 參照擷取這項中繼資料。

// Create reference to the file whose metadata we want to retrieve
StorageReference forestRef =
    storageRef.Child("images/forest.jpg");

// Get metadata properties
forestRef.GetMetadataAsync().ContinueWithOnMainThread(task => {
    if (!task.IsFaulted && !task.IsCanceled) {
        StorageMetadata meta = task.Result;
        // do stuff with meta
    }
});

更新檔案中繼資料

檔案上傳完成後,您隨時可以使用 UpdateMetadataAsync 方法 (採用 MetadataChange 物件) 更新檔案中繼資料。如要進一步瞭解可更新的屬性,請參閱完整清單。系統只會更新中繼資料中指定的屬性,其餘屬性則保持不變。

// Create reference to the file whose metadata we want to change
StorageReference forestRef = storageRef.Child("images/forest.jpg");

// Create file metadata to update
var newMetadata = new MetadataChange();
newMetadata.CacheControl = "public,max-age=300";
newMetadata.ContentType = "image/jpeg";

// Update metadata properties
forestRef.UpdateMetadataAsync(newMetadata).ContinueWithOnMainThread(task => {
    if (!task.IsFaulted && !task.IsCanceled) {
        // access the updated meta data
        StorageMetadata meta = task.Result;
    }
});

您可以傳遞空字串,刪除可寫入的中繼資料屬性:

// Create file metadata to update
var newMetadata = new MetadataChange();
newMetadata.ContentType = "";

// Update metadata properties
forestRef.UpdateMetadataAsync(newMetadata).ContinueWithOnMainThread(task => {
    if (!task.IsFaulted && !task.IsCanceled) {
        StorageMetadata meta = task.Result;
        // meta.ContentType should be an empty string now
    }
});

處理錯誤

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

自訂中繼資料

您可以將自訂中繼資料指定為 Dictionary<string, string>。

var newMetadata = new MetadataChange {
    CustomMetadata = new Dictionary<string, string> {
        {"location", "Yosemite, CA, USA"},
        {"activity", "Hiking"}
    }
};

// UpdateMetadataAsync

您可以在自訂中繼資料中儲存每個檔案的應用程式專屬資料,但強烈建議使用資料庫 (例如 Firebase Realtime Database) 儲存及同步處理這類資料。

檔案中繼資料屬性

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

屬性 類型 可在 MetadataChange 中修改
Bucket string 否
Generation string 否
MetadataGeneration string 否
Path string 否
Name string 否
SizeBytes long 否
CreationTimeMillis long 否
UpdatedTimeMillis long 否
CacheControl string 是
ContentDisposition string 是
ContentEncoding string 是
ContentLanguage string 是
ContentType string 是
DownloadUrl Uri 否
DownloadUrls IList<Uri> 否
CustomMetadataKeys IEnumerable<string> 是

後續步驟

上傳、下載和更新檔案固然重要,但能夠移除檔案也同樣重要。接著,我們來瞭解如何從 Cloud Storage 刪除檔案。