Unity용 Cloud Storage로 파일 업로드

Firebase용 Cloud Storage를 사용하면 Firebase에서 제공하고 관리하는 Cloud Storage 버킷에 파일을 빠르고 손쉽게 업로드할 수 있습니다.

참조 만들기

파일을 업로드하려면 우선 업로드할 파일을 가리키는 Cloud Storage 참조를 만듭니다.

Cloud Storage 버킷의 루트에 하위 경로를 추가하여 참조를 만들거나 Cloud Storage의 객체를 참조하는 기존 gs:// 또는 https:// URL로 참조를 만들 수 있습니다.

// 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 버킷의 루트를 가리키는 참조로는 데이터를 업로드할 수 없습니다. 참조는 하위 URL을 가리켜야 합니다.

파일 업로드

참조가 만들어졌으면 2가지 방법으로 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() 메서드를 사용합니다. 자세한 내용은 업로드 관리를 참조하세요.

파일 메타데이터 추가

파일을 업로드할 때 메타데이터를 포함할 수도 있습니다. 이 메타데이터는 Name, Size, ContentType(통칭 MIME 형식) 등의 일반적인 파일 메타데이터 속성을 포함합니다. PutFileAsync() 메서드를 사용하면 파일 이름 확장자에서 콘텐츠 유형이 자동으로 추론되지만, 메타데이터에 ContentType을 지정하면 자동 감지된 유형을 재정의할 수 있습니다. ContentType을 지정하지 않았고 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에서 파일을 다운로드하는 방법을 알아보세요.