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

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

可建立參照

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

您可以在 Cloud Storage 值區,或者您也可以從現有 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() 會採用 位元組 [] 並傳回 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> 存取 API您可以使用 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 執行