Tải tệp lên bằng Cloud Storage dành cho Unity

Trang này mô tả cách sử dụng SDK Cloud Storage for Firebase để tải tệp lên một bộ chứa Cloud Storage.

Để biết thêm thông tin, hãy xem phần Câu hỏi thường gặp này.

Tạo tệp đối chiếu

Để tải tệp lên, trước tiên, hãy tạo một Cloud Storage tệp đối chiếu đến tệp bạn muốn tải lên.

Bạn có thể tạo tệp đối chiếu bằng cách thêm đường dẫn con vào thư mục gốc của bộ chứa Cloud Storage hoặc có thể tạo tệp đối chiếu từ URL gs:// hoặc https:// hiện có tham chiếu đến một đối tượng trong 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);

Bạn không thể tải dữ liệu lên bằng tệp đối chiếu đến thư mục gốc của bộ chứa Cloud Storage. Tệp đối chiếu phải trỏ đến một URL con.

Tải tệp lên

Sau khi có tệp đối chiếu, bạn có thể tải tệp lên Cloud Storage theo hai cách:

  1. Tải lên từ một mảng byte trong bộ nhớ
  2. Tải lên từ đường dẫn tệp đại diện cho một tệp trên thiết bị

Tải lên từ dữ liệu trong bộ nhớ

Phương thức PutBytesAsync() là cách đơn giản nhất để tải tệp lên Cloud Storage. PutBytesAsync() nhận một byte[] và trả về một System.Task<Firebase.Storage.StorageMetadata> chứa thông tin về tệp khi tác vụ hoàn tất. Bạn có thể tuỳ ý sử dụng IProgress<UploadState> (thường là StorageProgress<UploadState>) để theo dõi trạng thái tải lên.

// 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);
        }
    });

Tải lên từ một tệp trên máy

Bạn có thể tải các tệp trên thiết bị lên, chẳng hạn như ảnh và video từ máy ảnh, bằng phương thức PutFileAsync(). PutFileAsync() lấy một string đại diện cho đường dẫn đến tệp và trả về một System.Task<Firebase.Storage.StorageMetadata> sẽ chứa thông tin về tệp khi tác vụ hoàn tất. Bạn có thể tuỳ ý sử dụng IProgress<UploadState> (thường là StorageProgress<UploadState>) để theo dõi trạng thái tải lên.

// 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);
        }
    });

Nếu muốn chủ động theo dõi quá trình tải lên, bạn có thể sử dụng lớp StorageProgress hoặc lớp của riêng bạn triển khai IProgress<UploadState>, bằng phương thức PutFileAsync hoặc PutBytesAsync. Để biết thêm thông tin, hãy xem bài viết Theo dõi tiến trình tải lên.

Thêm siêu dữ liệu của tệp

Bạn cũng có thể thêm siêu dữ liệu khi tải tệp lên. Siêu dữ liệu này chứa các thuộc tính siêu dữ liệu tệp thông thường như Name, Size và ContentType (thường được gọi là loại MIME). Phương thức PutFileAsync tự động suy luận loại MIME từ đuôi tên tệp, nhưng bạn có thể ghi đè loại được phát hiện tự động bằng cách chỉ định ContentType trong siêu dữ liệu. Nếu bạn không cung cấp ContentType và Cloud Storage không thể suy luận giá trị mặc định từ đuôi tệp, thì Cloud Storage sẽ sử dụng application/octet-stream. Để biết thêm thông tin về siêu dữ liệu của tệp, hãy xem bài viết Sử dụng siêu dữ liệu của tệp.

// 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(...

Theo dõi tiến trình tải lên

Bạn có thể đính kèm trình nghe vào các tệp tải lên để theo dõi tiến trình tải lên. Trình nghe tuân theo giao diện System.IProgress<T> chuẩn. Bạn có thể sử dụng một thực thể của lớp StorageProgress để cung cấp Action<T> của riêng bạn dưới dạng lệnh gọi lại cho các dấu kiểm tiến trình.

// 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.");
    }
});

Xử lý lỗi

Có một số lý do khiến lỗi có thể xảy ra khi tải lên, bao gồm cả việc tệp cục bộ không tồn tại hoặc người dùng không có quyền tải tệp dự kiến lên. Để biết thêm thông tin về lỗi, hãy xem phần Xử lý lỗi.

Các bước tiếp theo

Sau khi tải tệp lên, hãy tìm hiểu cách tải tệp xuống từ Cloud Storage.