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

Cloud Storage cho Firebase giúp bạn nhanh chóng và dễ dàng tải tệp lên Đã cung cấp bộ chứa Cloud Storage và được Firebase quản lý.

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

Để tải một tệp lên, trước tiên tạo tệp đối chiếu trong Cloud Storage vào vị trí trong Cloud Storage mà bạn muốn tải tệp lên.

Bạn có thể tạo tham 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 lên dữ liệu có tham chiếu đến thư mục gốc của Bộ chứa Cloud Storage. Tham chiếu của bạn 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 2 cách:

  1. Tải lên từ vùng đệm byte trong bộ nhớ
  2. Tải lên từ mộ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 giá trị Future<Metadata> sẽ chứa thông tin về tệp khi Tương lai hoàn tất. Bạn có thể sử dụng Controller để quản lý việc tải lên và theo dõi trạng thái của nó.

// 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 đưa ra nhưng chúng ta phải đợi Tương lai hoàn tất trước khi tải tệp lên. Vì trò chơi thường chạy theo vòng lặp và ít được thực hiện bằng lệnh gọi lại hơn so với các ứng dụng khác, bạn thường sẽ thăm dò hoàn thành.

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ừ một tệp trên máy

Bạn có thể tải lên các tệp cục bộ trên thiết bị, chẳng hạn như ảnh và video từ camera bằng phương thức PutFile(). PutFile() mất std::string biểu thị đường dẫn đến tệp và trả về một Future<Metadata> sẽ chứa về tệp khi Tương lai 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 tải lên.

// 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ý tệp tải lên, bạn có thể cung cấp Controller cho Phương thức PutFile() hoặc PutBytes(). Điều này cho phép bạn sử dụng bộ điều khiển để quan sát hoạt động tải lên đang diễn ra. Xem phần Quản lý tải lên cho 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 của tệp điển hình như name, sizecontent_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ệ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 ra giá trị mặc định từ đuôi tệp mà Cloud Storage sử dụng là application/octet-stream. Xem 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ỷ quá trình tải lên bằng cách sử dụng phương thức Pause(), Resume()Cancel() trên Controller. Bạn có thể nếu muốn truyền vào 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 nội dung tải lên để theo dõi tiến trình của 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 tệp cục bộ không tồn tại hoặc người dùng không có quyền tải lên tệp mong muốn. Bạn có thể tìm thêm thông tin về các lỗi trong phần Xử lý lỗi của phần Tài liệu.

Các bước tiếp theo

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