העלה קבצים עם Cloud Storage for 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 שלך. ההפניה שלך חייבת להפנות לכתובת אתר בת.

העלה קבצים

ברגע שיש לך הפניה, תוכל להעלות קבצים ל-Cloud Storage בשתי דרכים:

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

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

שיטת PutBytesAsync() היא הדרך הפשוטה ביותר להעלות קובץ ל-Cloud Storage. PutBytesAsync() לוקח byte[] ומחזיר 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(...

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

ניתן לצרף מאזינים להעלאות על מנת לעקוב אחר התקדמות ההעלאה. המאזין עוקב אחר ממשק System.IProgress<T> הסטנדרטי. אתה יכול להשתמש במופע של המחלקה StorageProgress , כדי לספק Action<T> משלך כקריאה חוזרת לתקתק התקדמות.

// 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.