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

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

可建立參照

如要上傳檔案,請先為要上傳的檔案建立 Cloud Storage 參考資料

您可以將子項路徑附加至 Cloud Storage 值區的根目錄,藉此建立參照,或是透過參照 Cloud Storage 中物件的現有 gs://https:// 網址建立參照。

// 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. 從代表裝置上檔案的檔案路徑上傳

從記憶體中的資料上傳

如要將檔案上傳至 Cloud Storage,使用 PutBytesAsync() 方法是最簡單的方法。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 類別,或藉由 PutFileAsync()PutBytesAsync() 方法導入 IProgress<UploadState> 的專屬類別。詳情請參閱「管理上傳項目」。

新增檔案中繼資料

您也可以在上傳檔案時加入中繼資料。這個中繼資料包含一般檔案中繼資料屬性,例如 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 下載這些檔案