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

Cloud Storage cho Firebase giúp bạn tải xuống nhanh chóng và dễ dàng tệp từ Cloud Storage bộ chứa do Firebase cung cấp và quản lý.

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

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

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 hoặc bạn có thể tạo tệp đối chiếu từ một tệp URL gs:// hoặc https:// 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 các tệp xuống từ Cloud Storage 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(). Chiến dịch này là cách dễ dàng nhất để nhanh chóng tải một tệp xuống, nhưng tệp 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 tệp lớn hơn kích thước của ứng dụng bộ nhớ còn trống thì ứng dụng của bạn sẽ gặp sự cố. Để ngăn chặn các vấn đề về bộ nhớ, hãy hãy đặt kích thước tối đa thành kích thước mà bạn biết ứ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 trước khi chúng tôi có thể đọc tệp. 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.

// 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ộ. 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 ngoại tuyến 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 một URL cần chia sẻ, bạn có thể lấy URL tải xuống của một tệp bằng cách gọi hàm Phương thức GetDownloadUrl() trên một tệp tham chiếu trong 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 mà bạn có thể tuỳ ý chuyển đến 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 của 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 khiến lỗi có thể 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 tệp mong muốn. Bạn có thể xem thêm thông tin về các lỗi trong Xử lý lỗi của phần Tài liệu.

Các bước tiếp theo

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