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

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

העלאת קבצים

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

Kotlin+KTX

// Create a storage reference from our app
val storageRef = storage.reference

// Create a reference to "mountains.jpg"
val mountainsRef = storageRef.child("mountains.jpg")

// Create a reference to 'images/mountains.jpg'
val mountainImagesRef = storageRef.child("images/mountains.jpg")

// While the file names are the same, the references point to different files
mountainsRef.name == mountainImagesRef.name // true
mountainsRef.path == mountainImagesRef.path // false

Java

// Create a storage reference from our app
StorageReference storageRef = storage.getReference();

// 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
mountainsRef.getName().equals(mountainImagesRef.getName());    // true
mountainsRef.getPath().equals(mountainImagesRef.getPath());    // false

לאחר יצירת קובץ עזר מתאים, קוראים אל putBytes(), putFile() או putStream() להעלאת הקובץ אל Cloud Storage.

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

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

השיטה putBytes() היא הדרך הפשוטה ביותר להעלות אל Cloud Storage. הפונקציה putBytes() לוקחת byte[] ומחזירה UploadTask שבאמצעותו אפשר לנהל את סטטוס ההעלאה ולעקוב אחרי סטטוס ההעלאה.

Kotlin+KTX

// Get the data from an ImageView as bytes
imageView.isDrawingCacheEnabled = true
imageView.buildDrawingCache()
val bitmap = (imageView.drawable as BitmapDrawable).bitmap
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()

var uploadTask = mountainsRef.putBytes(data)
uploadTask.addOnFailureListener {
    // Handle unsuccessful uploads
}.addOnSuccessListener { taskSnapshot ->
    // taskSnapshot.metadata contains file metadata such as size, content-type, etc.
    // ...
}

Java

// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();

UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
        // ...
    }
});

האפליקציה putBytes() מקבלת byte[], לכן האפליקציה צריכה להכיל את כל תוכן של קובץ בזיכרון בבת אחת. כדאי להשתמש ב-putStream() או putFile() כדי להשתמש פחות בזיכרון.

העלאה מזרם

השיטה putStream() היא הדרך המגוונת ביותר להעלות אל Cloud Storage. putStream() לוקחת InputStream וחוזרת UploadTask שאפשר להשתמש בו כדי לנהל את סטטוס ההעלאה ולעקוב אחריו.

Kotlin+KTX

val stream = FileInputStream(File("path/to/images/rivers.jpg"))

uploadTask = mountainsRef.putStream(stream)
uploadTask.addOnFailureListener {
    // Handle unsuccessful uploads
}.addOnSuccessListener { taskSnapshot ->
    // taskSnapshot.metadata contains file metadata such as size, content-type, etc.
    // ...
}

Java

InputStream stream = new FileInputStream(new File("path/to/images/rivers.jpg"));

uploadTask = mountainsRef.putStream(stream);
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
        // ...
    }
});

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

אפשר להעלות קבצים מקומיים למכשיר, כמו תמונות וסרטונים מצלמה באמצעות השיטה putFile(). הפונקציה putFile() לוקחת File ומחזירה UploadTask שבאמצעותו אפשר לנהל את סטטוס ההעלאה ולעקוב אחרי סטטוס ההעלאה.

Kotlin+KTX

var file = Uri.fromFile(File("path/to/images/rivers.jpg"))
val riversRef = storageRef.child("images/${file.lastPathSegment}")
uploadTask = riversRef.putFile(file)

// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener {
    // Handle unsuccessful uploads
}.addOnSuccessListener { taskSnapshot ->
    // taskSnapshot.metadata contains file metadata such as size, content-type, etc.
    // ...
}

Java

Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
        // ...
    }
});

קבלת כתובת URL להורדה

לאחר העלאת קובץ, אתם יכולים לקבל כתובת URL להורדת הקובץ באמצעות שליחת קריאה השיטה getDownloadUrl() ב-StorageReference:

Kotlin+KTX

val ref = storageRef.child("images/mountains.jpg")
uploadTask = ref.putFile(file)

val urlTask = uploadTask.continueWithTask { task ->
    if (!task.isSuccessful) {
        task.exception?.let {
            throw it
        }
    }
    ref.downloadUrl
}.addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val downloadUri = task.result
    } else {
        // Handle failures
        // ...
    }
}

Java

final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);

Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }

        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
        } else {
            // Handle failures
            // ...
        }
    }
});

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

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

Kotlin+KTX

// Create file metadata including the content type
var metadata = storageMetadata {
    contentType = "image/jpg"
}

// Upload the file and metadata
uploadTask = storageRef.child("images/mountains.jpg").putFile(file, metadata)

Java

// Create file metadata including the content type
StorageMetadata metadata = new StorageMetadata.Builder()
        .setContentType("image/jpg")
        .build();

// Upload the file and metadata
uploadTask = storageRef.child("images/mountains.jpg").putFile(file, metadata);

נהל העלאות

בנוסף להתחלת העלאות, ניתן להשהות, להמשיך ולבטל העלאות באמצעות pause(), resume() ו-cancel(). השהיה והמשך של אירועים הגדלת השינויים במצב pause וב-progress בהתאמה. ביטול ההעלאה גורם לכך שההעלאה נכשלת עם הודעת שגיאה שמציינת שההעלאה בוטלה.

Kotlin+KTX

uploadTask = storageRef.child("images/mountains.jpg").putFile(file)

// Pause the upload
uploadTask.pause()

// Resume the upload
uploadTask.resume()

// Cancel the upload
uploadTask.cancel()

Java

uploadTask = storageRef.child("images/mountains.jpg").putFile(file);

// Pause the upload
uploadTask.pause();

// Resume the upload
uploadTask.resume();

// Cancel the upload
uploadTask.cancel();

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

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

סוג מאזין שימוש רגיל
OnProgressListener ה-listener הזה נקרא מדי פעם בזמן העברת הנתונים, ואפשר להשתמש בו כדי לאכלס אינדיקטור של העלאה/הורדה.
OnPausedListener ה-listener הזה נקרא בכל פעם שהמשימה מושהית.
OnSuccessListener הבורר הזה נקרא כשהמשימה הושלמה בהצלחה.
OnFailureListener ה-listener הזה נקרא בכל פעם שההעלאה נכשלה. מצב כזה יכול לקרות בגלל זמנים קצובים לתפוגה של הרשת, כשלים בהרשאות או בגלל ביטול המשימה.

הפונקציה OnFailureListener מופעלת באמצעות מכונה של Exception. אחרים מתבצעים באמצעות אובייקט UploadTask.TaskSnapshot. האובייקט הזה הוא תצוגה קבועה של המשימה בזמן האירוע. UploadTask.TaskSnapshot מכיל את המאפיינים (properties) הבאים:

נכס סוג תיאור
getDownloadUrl String כתובת URL שאפשר להשתמש בה להורדת האובייקט. זוהי כתובת URL ציבורית שאי אפשר לנחש, שאפשר לשתף עם לקוחות אחרים. הערך הזה מאוכלס בסיום ההעלאה.
getError Exception אם המשימה נכשלה, הסיבה לכך היא חריגה.
getBytesTransferred long המספר הכולל של הבייטים שהועברו כשתמונת המצב הזו צולמה.
getTotalByteCount long המספר הכולל של הבייטים שצפויים להעלות.
getUploadSessionUri String URI שאפשר להשתמש בו כדי להמשיך את המשימה הזו דרך קריאה אחרת ל-putFile.
getMetadata StorageMetadata לפני שההעלאה מסתיימת, אלה המטא-נתונים שנשלחים לשרת. בסיום ההעלאה, אלו המטא-נתונים שהוחזרו על ידי השרת.
getTask UploadTask המשימה שיצרה את תמונת המצב הזו. במשימה הזו אפשר לבטל, להשהות או להמשיך את ההעלאה.
getStorage StorageReference השדה StorageReference ששימש ליצירת ה-UploadTask.

פונקציות event listener של UploadTask מספקות דרך פשוטה ויעילה למעקב העלאת אירועים.

Kotlin+KTX

// Observe state change events such as progress, pause, and resume
// You'll need to import com.google.firebase.storage.component1 and
// com.google.firebase.storage.component2
uploadTask.addOnProgressListener { (bytesTransferred, totalByteCount) ->
    val progress = (100.0 * bytesTransferred) / totalByteCount
    Log.d(TAG, "Upload is $progress% done")
}.addOnPausedListener {
    Log.d(TAG, "Upload is paused")
}

Java

// Observe state change events such as progress, pause, and resume
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
        Log.d(TAG, "Upload is " + progress + "% done");
    }
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
        Log.d(TAG, "Upload is paused");
    }
});

איך מטפלים בשינויים במחזור החיים של הפעילות

ההעלאות ממשיכות ברקע גם לאחר שינויים במחזור החיים של הפעילות (למשל כשמציגים תיבת דו-שיח או מסתובבים במסך). מאזינים שצירפת גם יישארו מצורפים. הדבר עלול להוביל לתוצאות בלתי צפויות אם קוראים קריאה אחרי שהפעילות הופסקה.

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

הדוגמה הבאה ממחישה את זה וגם מראה איך לשמור על האחסון בנתיב ההפניה שבו נעשה שימוש.

Kotlin+KTX

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)

    // If there's an upload in progress, save the reference so you can query it later
    outState.putString("reference", storageRef.toString())
}

override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)

    // If there was an upload in progress, get its reference and create a new StorageReference
    val stringRef = savedInstanceState.getString("reference") ?: return

    storageRef = Firebase.storage.getReferenceFromUrl(stringRef)

    // Find all UploadTasks under this StorageReference (in this example, there should be one)

    val tasks = storageRef.activeUploadTasks

    if (tasks.size > 0) {
        // Get the task monitoring the upload
        val task = tasks[0]

        // Add new listeners to the task using an Activity scope
        task.addOnSuccessListener(this) {
            // Success!
            // ...
        }
    }
}

Java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // If there's an upload in progress, save the reference so you can query it later
    if (mStorageRef != null) {
        outState.putString("reference", mStorageRef.toString());
    }
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // If there was an upload in progress, get its reference and create a new StorageReference
    final String stringRef = savedInstanceState.getString("reference");
    if (stringRef == null) {
        return;
    }
    mStorageRef = FirebaseStorage.getInstance().getReferenceFromUrl(stringRef);

    // Find all UploadTasks under this StorageReference (in this example, there should be one)
    List<UploadTask> tasks = mStorageRef.getActiveUploadTasks();
    if (tasks.size() > 0) {
        // Get the task monitoring the upload
        UploadTask task = tasks.get(0);

        // Add new listeners to the task using an Activity scope
        task.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot state) {
                // Success!
                // ...
            }
        });
    }
}

getActiveUploadTasks מאחזר את כל משימות ההעלאה הפעילות ב- ומתחת שסופק, לכן ייתכן שיהיה עליך לבצע מספר משימות.

המשך העלאות בתהליך הפעלות מחדש

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

כדי לעשות זאת, מתחילים להעלות דרך putFile. ב-StorageTask שנוצר, קוראים ל-getUploadSessionUri ושומרים את הערך שנוצר באחסון מתמיד (כמו SharedPreferences).

Kotlin+KTX

uploadTask = storageRef.putFile(localFile)
uploadTask.addOnProgressListener { taskSnapshot ->
    sessionUri = taskSnapshot.uploadSessionUri
    if (sessionUri != null && !saved) {
        saved = true
        // A persisted session has begun with the server.
        // Save this to persistent storage in case the process dies.
    }
}

Java

uploadTask = mStorageRef.putFile(localFile);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
        Uri sessionUri = taskSnapshot.getUploadSessionUri();
        if (sessionUri != null && !mSaved) {
            mSaved = true;
            // A persisted session has begun with the server.
            // Save this to persistent storage in case the process dies.
        }
    }
});

אחרי שהתהליך יתחיל מחדש כשההעלאה הופסקה, צריך לקרוא שוב את המילה PutFile. אבל הפעם גם להעביר את ה-URI שנשמר.

Kotlin+KTX

// resume the upload task from where it left off when the process died.
// to do this, pass the sessionUri as the last parameter
uploadTask = storageRef.putFile(
    localFile,
    storageMetadata { },
    sessionUri,
)

Java

//resume the upload task from where it left off when the process died.
//to do this, pass the sessionUri as the last parameter
uploadTask = mStorageRef.putFile(localFile,
        new StorageMetadata.Builder().build(), sessionUri);

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

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

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

דוגמה מלאה

דוגמה מלאה להעלאה עם מעקב אחרי התקדמות וטיפול בשגיאות מוצגת כך:

Kotlin+KTX

// File or Blob
file = Uri.fromFile(File("path/to/mountains.jpg"))

// Create the file metadata
metadata = storageMetadata {
    contentType = "image/jpeg"
}

// Upload file and metadata to the path 'images/mountains.jpg'
uploadTask = storageRef.child("images/${file.lastPathSegment}").putFile(file, metadata)

// Listen for state changes, errors, and completion of the upload.
// You'll need to import com.google.firebase.storage.component1 and
// com.google.firebase.storage.component2
uploadTask.addOnProgressListener { (bytesTransferred, totalByteCount) ->
    val progress = (100.0 * bytesTransferred) / totalByteCount
    Log.d(TAG, "Upload is $progress% done")
}.addOnPausedListener {
    Log.d(TAG, "Upload is paused")
}.addOnFailureListener {
    // Handle unsuccessful uploads
}.addOnSuccessListener {
    // Handle successful uploads on complete
    // ...
}

Java

// File or Blob
file = Uri.fromFile(new File("path/to/mountains.jpg"));

// Create the file metadata
metadata = new StorageMetadata.Builder()
        .setContentType("image/jpeg")
        .build();

// Upload file and metadata to the path 'images/mountains.jpg'
uploadTask = storageRef.child("images/"+file.getLastPathSegment()).putFile(file, metadata);

// Listen for state changes, errors, and completion of the upload.
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
        Log.d(TAG, "Upload is " + progress + "% done");
    }
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
        Log.d(TAG, "Upload is paused");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // Handle successful uploads on complete
        // ...
    }
});

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