העלאת קבצים באמצעות Cloud Storage ל-Unity

Cloud Storage for Firebase מאפשר לך להעלות קבצים במהירות ובקלות סופקה קטגוריה של Cloud Storage ומנוהלות ב-Firebase.

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

כדי להעלות קובץ, קודם יצירת קובץ עזר של Cloud Storage לקובץ שרוצים להעלות.

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

// Create a root reference
StorageReference storageRef = storage.RootReference;

// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.Child("mountains.jpg");

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

// While the file names are the same, the references point to different files
Assert.AreEqual(mountainsRef.Name, mountainImagesRef.Name);
Assert.AreNotEqual(mountainsRef.Path, mountainImagesRef.Path);

אי אפשר להעלות נתונים עם הפניה לשורש הקטגוריה Cloud Storage. ההפניה חייבת להפנות לכתובת URL של צאצא.

העלאת קבצים

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

  1. העלאה ממערך בייטים בזיכרון
  2. העלאה מנתיב קובץ שמייצג קובץ במכשיר

העלאה מנתונים בזיכרון

השיטה PutBytesAsync() היא הדרך הפשוטה ביותר להעלות קובץ אל Cloud Storage. PutBytesAsync() לוקח בייט[] ומחזירה את הערך System.Task<Firebase.Storage.StorageMetadata> מכילים מידע על הקובץ בסיום המשימה. אפשר להשתמש ב-IProgress<UploadState> (בדרך כלל StorageProgress<UploadState>) כדי לעקוב אחר סטטוס ההעלאה שלכם.

// Data in memory
var customBytes = new byte[] {
    /*...*/
};

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

// Upload the file to the path "images/rivers.jpg"
riversRef.PutBytesAsync(customBytes)
    .ContinueWith((Task<StorageMetadata> task) => {
        if (task.IsFaulted || task.IsCanceled) {
            Debug.Log(task.Exception.ToString());
            // Uh-oh, an error occurred!
        }
        else {
            // Metadata contains file metadata such as size, content-type, and md5hash.
            StorageMetadata metadata = task.Result;
            string md5Hash = metadata.Md5Hash;
            Debug.Log("Finished uploading...");
            Debug.Log("md5 hash = " + md5Hash);
        }
    });

העלאה מקובץ מקומי

אפשר להעלות קבצים מקומיים במכשירים, כמו תמונות וסרטונים מהמצלמה, באמצעות השיטה PutFileAsync(). הפונקציה PutFileAsync() מקבלת string שמייצג את הנתיב לקובץ ומחזירה System.Task<Firebase.Storage.StorageMetadata> שיכיל מידע על הקובץ בסיום המשימה. אפשר להשתמש ב-IProgress<UploadState> (בדרך כלל StorageProgress<UploadState>) כדי לעקוב אחר סטטוס ההעלאה שלכם.

// File located on disk
string localFile = "...";

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

// Upload the file to the path "images/rivers.jpg"
riversRef.PutFileAsync(localFile)
    .ContinueWith((Task<StorageMetadata> task) => {
        if (task.IsFaulted || task.IsCanceled) {
            Debug.Log(task.Exception.ToString());
            // Uh-oh, an error occurred!
        }
        else {
            // Metadata contains file metadata such as size, content-type, and download URL.
            StorageMetadata metadata = task.Result;
            string md5Hash = metadata.Md5Hash;
            Debug.Log("Finished uploading...");
            Debug.Log("md5 hash = " + md5Hash);
        }
    });

אם אתם רוצים לעקוב באופן פעיל אחרי ההעלאה, תוכלו להשתמש בכיתה StorageProgress או בכיתה משלכם שמטמיעה את IProgress<UploadState>, עם השיטות PutFileAsync() או PutBytesAsync(). מידע נוסף זמין בניהול העלאות.

הוספת מטא-נתונים של קבצים

אפשר גם לכלול מטא-נתונים כשמעלים קבצים. המטא-נתונים האלה מכילים מאפיינים אופייניים של מטא-נתונים של קובץ, כמו Name, Size ו-ContentType (נקרא בדרך כלל סוג MIME). השיטה PutFileAsync() באופן אוטומטי מסיקה את סוג התוכן מהסיומת של שם הקובץ, אבל אפשר לשנות את סוג שזוהה באופן אוטומטי על ידי ציון ContentType במטא-נתונים. אם לא מספקים ContentType ו-Cloud Storage לא יכול להסיק ברירת מחדל סיומת הקובץ, Cloud Storage משתמשת ב-application/octet-stream. צפייה האפשרות שימוש במטא-נתונים של קבצים לקבלת מידע נוסף על המטא נתונים של הקבצים.

// Create storage reference
StorageReference mountainsRef = storageRef.Child("images/mountains.jpg");

byte[] customBytes = new byte[] {
    /*...*/
};
string localFile = "...";

// Create file metadata including the content type
var newMetadata = new MetadataChange();
newMetadata.ContentType = "image/jpeg";

// Upload data and metadata
mountainsRef.PutBytesAsync(customBytes, newMetadata, null,
    CancellationToken.None); // .ContinueWithOnMainThread(...
// Upload file and metadata
mountainsRef.PutFileAsync(localFile, newMetadata, null,
    CancellationToken.None); // .ContinueWithOnMainThread(...

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

אתם יכולים לצרף מאזינים להעלאות כדי לעקוב אחרי התקדמות ההעלאה. ה-listener פועל לפי System.IProgress<T> הסטנדרטי גרפי. אפשר להשתמש במופע של הכיתה StorageProgress כדי לספק Action<T> משלכם כפונקציית קריאה חוזרת (callback) לסימני התקדמות.

// Start uploading a file
var task = storageRef.Child("images/mountains.jpg")
    .PutFileAsync(localFile, null,
        new StorageProgress<UploadState>(state => {
            // called periodically during the upload
            Debug.Log(String.Format("Progress: {0} of {1} bytes transferred.",
                state.BytesTransferred, state.TotalByteCount));
        }), CancellationToken.None, null);

task.ContinueWithOnMainThread(resultTask => {
    if (!resultTask.IsFaulted && !resultTask.IsCanceled) {
        Debug.Log("Upload finished.");
    }
});

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

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

השלבים הבאים

עכשיו, אחרי שהעלית את הקבצים, נלמד איך להוריד אותם מ-Cloud Storage.