使用 Unity 適用的 Cloud Storage 上傳檔案

Cloud Storage for Firebase 可讓您快速輕鬆地將檔案上傳至 Firebase 提供及管理的 Cloud Storage bucket。

可建立參照

如要上傳檔案,請先建立要上傳檔案的 Cloud Storage 參照

您可以將子路徑附加至 Cloud Storage bucket 的根目錄,藉此建立參照,也可以從現有的 gs://https:// 網址建立參照,該網址參照 Cloud Storage 中的物件。

// Create a root reference
StorageReference storageRef = storage.RootReference;

// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.Child("mountains.jpg");

// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef =
    storageRef.Child("images/mountains.jpg");

// While the file names are the same, the references point to different files
Assert.AreEqual(mountainsRef.Name, mountainImagesRef.Name);
Assert.AreNotEqual(mountainsRef.Path, mountainImagesRef.Path);

您無法上傳參照 Cloud Storage 值區根目錄的資料。參照必須指向子網址。

上傳檔案

取得參照後,即可透過兩種方式將檔案上傳至 Cloud Storage

  1. 從記憶體中的位元組陣列上傳
  2. 從代表裝置上檔案的檔案路徑上傳

從記憶體中的資料上傳

PutBytesAsync() 方法是將檔案上傳至 Cloud Storage 的最簡單方式。PutBytesAsync() 會採用 byte[],並傳回 System.Task<Firebase.Storage.StorageMetadata>,其中包含工作完成時的檔案相關資訊。您可以選擇使用 IProgress<UploadState> (通常是 StorageProgress<UploadState>) 監控上傳狀態。

// Data in memory
var customBytes = new byte[] {
    /*...*/
};

// Create a reference to the file you want to upload
StorageReference riversRef = storageRef.Child("images/rivers.jpg");

// Upload the file to the path "images/rivers.jpg"
riversRef.PutBytesAsync(customBytes)
    .ContinueWith((Task<StorageMetadata> task) => {
        if (task.IsFaulted || task.IsCanceled) {
            Debug.Log(task.Exception.ToString());
            // Uh-oh, an error occurred!
        }
        else {
            // Metadata contains file metadata such as size, content-type, and md5hash.
            StorageMetadata metadata = task.Result;
            string md5Hash = metadata.Md5Hash;
            Debug.Log("Finished uploading...");
            Debug.Log("md5 hash = " + md5Hash);
        }
    });

從本機檔案上傳

你可以使用 PutFileAsync() 方法,上傳裝置上的本機檔案,例如相機中的相片和影片。PutFileAsync() 會採用代表檔案路徑的 string,並傳回 System.Task<Firebase.Storage.StorageMetadata>,其中包含工作完成時的檔案相關資訊。您可以選擇使用 IProgress<UploadState> (通常是 StorageProgress<UploadState>) 監控上傳狀態。

// File located on disk
string localFile = "...";

// Create a reference to the file you want to upload
StorageReference riversRef = storageRef.Child("images/rivers.jpg");

// Upload the file to the path "images/rivers.jpg"
riversRef.PutFileAsync(localFile)
    .ContinueWith((Task<StorageMetadata> task) => {
        if (task.IsFaulted || task.IsCanceled) {
            Debug.Log(task.Exception.ToString());
            // Uh-oh, an error occurred!
        }
        else {
            // Metadata contains file metadata such as size, content-type, and download URL.
            StorageMetadata metadata = task.Result;
            string md5Hash = metadata.Md5Hash;
            Debug.Log("Finished uploading...");
            Debug.Log("md5 hash = " + md5Hash);
        }
    });

如要主動監控上傳作業,可以使用 StorageProgress 類別或實作 IProgress<UploadState> 的自有類別,搭配 PutFileAsync()PutBytesAsync() 方法。詳情請參閱「管理上傳作業」。

新增檔案中繼資料

上傳檔案時,您也可以加入中繼資料。這項中繼資料包含一般檔案中繼資料屬性,例如 NameSizeContentType (通常稱為 MIME 類型)。PutFileAsync() 方法會根據檔案名稱副檔名自動推斷內容類型,但您可以在中繼資料中指定 ContentType,覆寫自動偵測到的類型。如果您未提供 ContentType,且 Cloud Storage 無法從副檔名推斷預設值,Cloud Storage 就會使用 application/octet-stream。如要進一步瞭解檔案中繼資料,請參閱「使用檔案中繼資料」一節。

// Create storage reference
StorageReference mountainsRef = storageRef.Child("images/mountains.jpg");

byte[] customBytes = new byte[] {
    /*...*/
};
string localFile = "...";

// Create file metadata including the content type
var newMetadata = new MetadataChange();
newMetadata.ContentType = "image/jpeg";

// Upload data and metadata
mountainsRef.PutBytesAsync(customBytes, newMetadata, null,
    CancellationToken.None); // .ContinueWithOnMainThread(...
// Upload file and metadata
mountainsRef.PutFileAsync(localFile, newMetadata, null,
    CancellationToken.None); // .ContinueWithOnMainThread(...

監控上傳進度

你可以將監聽器附加至上傳作業,監控上傳進度。這個監聽器遵循標準 System.IProgress<T> 介面。您可以使用 StorageProgress 類別的執行個體,將自己的 Action<T> 做為進度刻度的回呼。

// Start uploading a file
var task = storageRef.Child("images/mountains.jpg")
    .PutFileAsync(localFile, null,
        new StorageProgress<UploadState>(state => {
            // called periodically during the upload
            Debug.Log(String.Format("Progress: {0} of {1} bytes transferred.",
                state.BytesTransferred, state.TotalByteCount));
        }), CancellationToken.None, null);

task.ContinueWithOnMainThread(resultTask => {
    if (!resultTask.IsFaulted && !resultTask.IsCanceled) {
        Debug.Log("Upload finished.");
    }
});

處理錯誤

上傳時發生錯誤的原因有很多,包括本機檔案不存在,或是使用者沒有上傳所需檔案的權限。如要進一步瞭解錯誤,請參閱說明文件的「處理錯誤」一節。

後續步驟

上傳檔案後,接著請參閱這篇文章,瞭解如何從 Cloud Storage 下載檔案。