Tải tệp xuống bằng Cloud Storage cho C++

Cloud Storage cho Firebase giúp bạn tải các tệp xuống 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 một tệp xuống, trước tiên, hãy tạo một tệp tham chiếu trên Cloud Storage cho tệp bạn muốn tải xuống.

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 bạn 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 reference with an initial file path and name
StorageReference path_reference = storage->GetReference("images/stars.jpg");

// Create a reference from a Cloud Storage URI
StorageReference gs_reference = storage->GetReferenceFromUrl("gs://bucket/images/stars.jpg");

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
StorageReference https_reference = storage->GetReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");

Tệp tải xuống

Sau khi có tệp đối chiếu, bạn có thể tải tệp từ Cloud Storage xuống theo 3 cách:

  1. Tải xuống một vùng đệm trong bộ nhớ
  2. Tải xuống một đường dẫn cụ thể trên thiết bị
  3. Tạo một URL chuỗi đại diện cho tệp trực tuyến

Tải xuống trong bộ nhớ

Tải tệp xuống vùng đệm byte trong bộ nhớ bằng phương thức GetBytes(). Đây là cách dễ nhất để nhanh chóng tải một tệp xuống, nhưng phải tải toàn bộ nội dung của tệp vào bộ nhớ. Nếu bạn yêu cầu một tệp lớn hơn bộ nhớ hiện có của ứng dụng, ứng dụng sẽ gặp sự cố. Để tránh các vấn đề về bộ nhớ, hãy nhớ đặt kích thước tối đa thành kích thước mà bạn biết rằng ứng dụng của mình có thể xử lý hoặc sử dụng một phương thức tải xuống khác.

// Create a reference to the file you want to download
StorageReference island_ref = storage_ref.Child("images/island.jpg");

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
const size_t kMaxAllowedSize = 1 * 1024 * 1024
int8_t byte_buffer[kMaxAllowedSize];
firebase::Future future = island_ref.GetBytes(byte_buffer, kMaxAllowedSize);

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 thì mới có thể đọc tệp. Vì trò chơi thường chạy trong một vòng lặp và ít được thực hiện lệnh gọi lại hơn so với các ứng dụng khác, nên bạn thường sẽ thăm dò ý kiến để hoàn tất.

// In the game loop that polls for the result...

if (future.status() != firebase::kFutureStatusPending) {
  if (future.status() != firebase::kFutureStatusComplete) {
    LogMessage("ERROR: GetBytes() returned an invalid future.");
    // Handle the error...
  } else if (future.Error() != firebase::storage::kErrorNone) {
    LogMessage("ERROR: GetBytes() returned error %d: %s", future.Error(),
               future.error_message());
    // Handle the error...
  } else {
    // byte_buffer is now populated with data for "images/island.jpg"
  }
}

Tải xuống tệp cục bộ

Phương thức GetFile() sẽ tải tệp trực tiếp xuống thiết bị cục bộ. Hãy sử dụng cách này nếu người dùng của bạn muốn có quyền truy cập vào tệp khi không có mạng hoặc để chia sẻ trong một ứng dụng khác.

// Create a reference to the file you want to download
StorageReference islandRef = storage_ref.Child("images/island.jpg"];

// Create local filesystem URL
const char* local_url = "file:///local/images/island.jpg";

// Download to the local filesystem
Future future = islandRef.GetFile(local_url);

// Wait for Future to complete...

if (future.Error() != firebase::storage::kErrorNone) {
  // Uh-oh, an error occurred!
} else {
  // The file has been downloaded to local file URL "images/island.jpg"
}

GetFile() lấy một đối số Controller (không bắt buộc) mà bạn có thể dùng để quản lý tệp đã tải xuống. Xem phần Quản lý tài nguyên tải xuống để biết thêm thông tin.

Tạo URL tải xuống

Nếu đã có cơ sở hạ tầng tải xuống dựa trên URL hoặc chỉ muốn chia sẻ URL, bạn có thể lấy URL tải xuống cho một tệp bằng cách gọi phương thức GetDownloadUrl() trên một tệp tham chiếu của Cloud Storage.

// Create a reference to the file you want to download
StorageReference stars_ref = storage_ref.Child("images/stars.jpg");

// Fetch the download URL
firebase::Future future = stars_ref.GetDownloadUrl();

// Wait for Future to complete...

if (future.Error() != firebase::storage::kErrorNone) {
  // Uh-oh, an error occurred!
} else {
  // Get the download URL for 'images/stars.jpg'
  std::string download_url = future.Result();
}

Quản lý tệp đã tải xuống

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

// Start downloading a file
Controller controller;
storage_ref.Child("images/mountains.jpg").GetFile(local_file, nullptr, &controller);

// Pause the download
controller.Pause();

// Resume the download
controller.Resume();

// Cancel the download
controller.Cancel();

Theo dõi tiến trình tải xuống

Bạn có thể đính kèm trình nghe vào tệp đã tải xuống để theo dõi tiến trình tải xuống.

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").GetFile(local_file, my_listener);
}

Xử lý lỗi

Có một số lý do có thể khiến lỗi xảy ra khi tải xuống, bao gồm tệp không tồn tại hoặc người dùng không có quyền truy cập vào tệp mong muốn. Bạn có thể xem 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

Bạn cũng có thể lấy và cập nhật siêu dữ liệu cho các tệp được lưu trữ trong Cloud Storage.