הורדת קבצים באמצעות Cloud Storage ל-C++

Cloud Storage for Firebase מאפשר לכם להוריד במהירות ובקלות קבצים ממאגר (bucket) של Cloud Storage שסופק ומנוהל על ידי Firebase.

יצירת קובץ עזר

כדי להוריד קובץ, קודם צריך ליצור הפניה Cloud Storage לקובץ שרוצים להוריד.

כדי ליצור הפניה, אפשר להוסיף נתיבי צאצא לשורש של קטגוריית Cloud Storage, או ליצור הפניה מכתובת URL קיימת של Cloud Storage או של https:// שמפנה לאובייקט ב-Cloud Storage.gs://

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

הורדת קבצים

אחרי שיש לכם קובץ עזר, אתם יכולים להוריד קבצים מCloud Storage בשלוש דרכים:

  1. הורדה למאגר נתונים זמני בזיכרון
  2. הורדה לנתיב ספציפי במכשיר
  3. יצירת כתובת URL של מחרוזת שמייצגת את הקובץ באינטרנט

הורדה בזיכרון

מורידים את הקובץ למאגר בייטים בזיכרון באמצעות ה-method‏ GetBytes(). זו הדרך הכי קלה להוריד קובץ במהירות, אבל צריך לטעון את כל התוכן של הקובץ לזיכרון. אם תבקשו קובץ גדול יותר מהזיכרון הזמין של האפליקציה, האפליקציה תקרוס. כדי להגן מפני בעיות בזיכרון, חשוב להגדיר את הגודל המקסימלי לערך שהאפליקציה יכולה להתמודד איתו, או להשתמש בשיטת הורדה אחרת.

// 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<size_t> future = island_ref.GetBytes(byte_buffer, kMaxAllowedSize);

בשלב שבו הבקשה נוצרה, אבל אנחנו צריכים לחכות עד שה-Future יושלם לפני שנוכל לקרוא את הקובץ. משחקים בדרך כלל פועלים בלולאה, והם מבוססים פחות על קריאות חוזרות בהשוואה לאפליקציות אחרות, ולכן בדרך כלל מתבצעת בדיקה חוזרת כדי לראות אם הפעולה הושלמה.

// 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"
  }
}

הורדה לקובץ מקומי

השיטה GetFile() מורידה קובץ ישירות למכשיר מקומי. משתמשים באפשרות הזו אם המשתמשים רוצים לגשת לקובץ במצב אופליין או לשתף אותו באפליקציה אחרת.

// 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<size_t> 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() מקבלת ארגומנט אופציונלי Controller שאפשר להשתמש בו כדי לנהל את ההורדה. מידע נוסף זמין במאמר בנושא ניהול ההורדות.

יצירת כתובת URL להורדה

אם כבר יש לכם תשתית להורדות שמבוססת על כתובות URL, או שאתם פשוט רוצים כתובת URL לשיתוף, אתם יכולים לקבל את כתובת ה-URL להורדה של קובץ על ידי קריאה לשיטה GetDownloadUrl() בהפניה 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<std::string> 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();
}

ניהול ההורדות

בנוסף להתחלת הורדות, אפשר להשהות, להמשיך ולבטל הורדות באמצעות השיטות Pause(), Resume() ו-Cancel() ב-Controller, שאפשר להעביר אותן לשיטות GetBytes() או 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();

מעקב אחרי התקדמות ההורדה

אפשר לצרף מאזינים להורדות כדי לעקוב אחרי ההתקדמות של ההורדה.

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

טיפול בשגיאות

יכולות להיות כמה סיבות לשגיאות בהורדה, כולל העובדה שהקובץ לא קיים או שאין למשתמש הרשאה לגשת לקובץ הרצוי. מידע נוסף על שגיאות זמין בקטע Handle Errors במסמכים.

השלבים הבאים

אפשר גם לקבל ולעדכן מטא-נתונים של קבצים שמאוחסנים ב-Cloud Storage.