Tải tệp lên bằng Cloud Storage cho C++

Cloud Storage for Firebase cho phép bạn tải tệp lên một bộ chứa Cloud Storage do Firebase cung cấp và quản lý một cách nhanh chóng và dễ dàng.

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

Để tải tệp lên, trước tiên, hãy tạo một tệp tham chiếu Cloud Storage đến vị trí trong Cloud Storage mà bạn muốn tải tệp 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:

// Create a root reference
StorageReference storage_ref = storage->GetReference();

// Create a reference to "mountains.jpg"
StorageReference mountains_ref = storage_ref.Child("mountains.jpg");

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

// While the file names are the same, the references point to different files
mountains_ref.name() == mountain_images_ref.name();           // true
mountains_ref.full_path() == mountain_images_ref.full_path(); // false

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 của bạn phải trỏ đến một URL con.

Tải lênTệp

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ừ vùng đệm 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 PutData() là cách đơn giản nhất để tải tệp lên Cloud Storage. PutData() lấy một vùng đệm byte và trả về một Future<Metadata> sẽ chứa thông tin về tệp khi Future hoàn tất. Bạn có thể sử dụng Controller để quản lý tệp tải lên và theo dõi trạng thái của tệp.

// Data in memory
const size_t kByteBufferSize = ...
uint8_t byte_buffer[kByteBufferSize] = { ... };

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

// Upload the file to the path "images/rivers.jpg"
Future future = rivers_ref.PutBytes(byte_buffer, kByteBufferSize);

Tại thời điểm yêu cầu được thực hiện, chúng ta phải đợi Future hoàn tất trước khi tệp được tải lên. Vì trò chơi thường chạy theo vòng lặp và ít dựa vào lệnh gọi lại hơn các ứng dụng khác, nên bạn thường sẽ thăm dò ý kiến để hoàn tất.

if (future.status() != firebase::kFutureStatusPending) {
  if (future.status() != firebase::kFutureStatusComplete) {
    LogMessage("ERROR: GetData() returned an invalid future.");
    // Handle the error...
  } else if (future.Error() != firebase::storage::kErrorNone) {
    LogMessage("ERROR: GetData() returned error %d: %s", future.Error(),
               future.error_message());
    // Handle the error...
    }
  } else {
    // Metadata contains file metadata such as size, content-type, and download URL.
    Metadata* metadata = future.Result();
    std::string download_url = metadata->download_url();
  }
}

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

Bạn có thể tải 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 PutFile(). PutFile() lấy một std::string đại diện cho đường dẫn đến tệp và trả về một Future<Metadata> sẽ chứa thông tin về tệp khi Future hoàn tất. Bạn có thể sử dụng Controller để quản lý quá trình tải lên và theo dõi trạng thái của quá trình này.

// File located on disk
std::string local_file = ...

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

// Upload the file to the path "images/rivers.jpg"
Future future = rivers_ref.PutFile(localFile);

// Wait for Future to complete...

if (future.Error() != firebase::storage::kErrorNone) {
  // Uh-oh, an error occurred!
} else {
  // Metadata contains file metadata such as size, content-type, and download URL.
  Metadata* metadata = future.Result();
  std::string download_url = metadata->download_url();
}

Nếu muốn chủ động quản lý quá trình tải lên, bạn có thể cung cấp Controller cho phương thức PutFile() hoặc PutBytes(). Nhờ đó, bạn có thể dùng trình điều khiển để quan sát hoạt động tải lên đang diễn ra. Hãy xem phần Quản lý tệp tải lên để biết thêm thông tin.

Thêm siêu dữ liệu 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à content_type (thường được gọi là loại MIME). Phương thức PutFile() tự động suy luận loại nội dung 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 content_type trong siêu dữ liệu. Nếu bạn không cung cấp content_type 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. Hãy xem phần Sử dụng siêu dữ liệu tệp để biết thêm thông tin về siêu dữ liệu tệp.

// Create storage reference
StorageReference mountains_ref = storage_ref.Child("images/mountains.jpg");

// Create file metadata including the content type
StorageMetadata metadata;
metadata.set_content_type("image/jpeg");

// Upload data and metadata
mountains_ref.PutBytes(data, metadata);

// Upload file and metadata
mountains_ref.PutFile(local_file, metadata);

Quản lý tải lên

Ngoài việc bắt đầu tải lên, bạn có thể tạm dừng, tiếp tục và huỷ tải lên bằng cách sử dụng các phương thức Pause(), Resume() và Cancel() trên Controller. Bạn có thể tuỳ ý chuyển các phương thức này sang phương thức PutBytes() hoặc PutFile().

// Start uploading a file
firebase::storage::Controller controller;
storage_ref.Child("images/mountains.jpg").PutFile(local_file, nullptr, &controller);

// Pause the upload
controller.Pause();

// Resume the upload
controller.Resume();

// Cancel the upload
controller.Cancel();

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.

class MyListener : public firebase::storage::Listener {
 public:
  virtual void OnProgress(firebase::storage::Controller* controller) {
    // A progress event occurred
  }
};

{
  // Start uploading a file
  MyEventListener my_listener;
  storage_ref.Child("images/mountains.jpg").PutFile(local_file, my_listener);
}

Lỗi xử lý

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 mong muốn lên. Bạn có thể tìm thêm thông tin về lỗi trong phần Xử lý lỗi của tài liệu.

Các bước tiếp theo

Giờ thì bạn đã tải tệp lên, hãy tìm hiểu cách tải tệp xuống từ Cloud Storage.