בדף הזה מוסבר איך להשתמש ב-SDK של Cloud Storage for Firebase כדי להעלות קבצים לקטגוריה של Cloud Storage.
מידע נוסף זמין בשאלות הנפוצות האלה.
העלאת קבצים
כדי להעלות קובץ אל Cloud Storage, קודם צריך ליצור הפניה לנתיב המלא של הקובץ, כולל שם הקובץ.
Kotlin
// 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.
אי אפשר להעלות נתונים עם הפניה לרמה הבסיסית (root) של הקטגוריה ב-Cloud Storage. ההפניה צריכה להצביע על כתובת URL צאצא.
העלאה מנתונים בזיכרון
השיטה putBytes() היא הדרך הפשוטה ביותר להעלות קובץ אל Cloud Storage. השיטה putBytes() מקבלת byte[] ומחזירה UploadTask שבו אפשר להשתמש כדי לנהל את סטטוס ההעלאה ולעקוב אחריו.
Kotlin
// Get the data from an ImageView as bytes imageView.isDrawingCacheEnabled = true imageView.buildDrawingCache() val bitmap = (imageView.drawable as BitmapDrawable).bitmap lifecycleScope.launch { val data = withContext(Dispatchers.Default) { val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) baos.toByteArray() } val 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(); Executors.newSingleThreadExecutor().execute(() -> { 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
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
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 להורדת הקובץ על ידי קריאה ל-method getDownloadUrl() ב-StorageReference:
Kotlin
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). ה-method putFile() מסיקה באופן אוטומטי את סוג ה-MIME מהסיומת File, אבל אפשר לשנות את הסוג שזוהה אוטומטית על ידי ציון contentType במטא-נתונים. אם לא תציינו contentType ו-Cloud Storage לא יוכל להסיק ברירת מחדל מסיומת הקובץ, Cloud Storage ישתמש ב-application/octet-stream. מידע נוסף על מטא-נתונים של קבצים זמין במאמר שימוש במטא-נתונים של קבצים.
Kotlin
// 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
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 |
המאזין הזה נקרא מדי פעם כשהנתונים מועברים, ואפשר להשתמש בו כדי לאכלס אינדיקטור של העלאה או הורדה. |
OnPausedListener |
המאזין הזה נקרא בכל פעם שהמשימה מושהית. |
OnSuccessListener |
המאזין הזה נקרא כשהמשימה הושלמה בהצלחה. |
OnFailureListener |
המאזין הזה נקרא בכל פעם שההעלאה נכשלת. זה יכול לקרות בגלל זמן קצוב לתפוגה של הרשת, כשלים בהרשאה או אם אתם מבטלים את המשימה. |
הפונקציה OnFailureListener נקראת עם מופע של Exception. מאזינים אחרים נקראים עם אובייקט UploadTask.TaskSnapshot.
האובייקט הזה הוא תצוגה קבועה של המשימה בזמן שהאירוע התרחש.
UploadTask.TaskSnapshot מכיל את המאפיינים הבאים:
| נכס | סוג | תיאור |
|---|---|---|
getDownloadUrl |
String |
כתובת URL שאפשר להשתמש בה כדי להוריד את האובייקט. זו כתובת URL ציבורית שלא ניתן לנחש אותה, ואפשר לשתף אותה עם לקוחות אחרים. הערך הזה מאוכלס אחרי שההעלאה מסתיימת. |
getError |
Exception |
אם המשימה נכשלה, הסיבה תופיע כחריגה. |
getBytesTransferred |
long |
המספר הכולל של בייטים שהועברו כשתמונת המצב הזו נוצרה. |
getTotalByteCount |
long |
המספר הכולל של בייטים שצפויים לעלות. |
getUploadSessionUri |
String |
URI שאפשר להשתמש בו כדי להמשיך את המשימה הזו באמצעות קריאה נוספת ל-putFile. |
getMetadata |
StorageMetadata |
לפני שההעלאה מסתיימת, אלה המטא-נתונים שנשלחים לשרת. אחרי שההעלאה מסתיימת, אלה המטא-נתונים שהשרת מחזיר. |
getTask |
UploadTask |
המשימה שיצרה את קובץ ה-snapshot הזה. כדי לבטל, להשהות או להמשיך את ההעלאה, משתמשים במשימה הזו. |
getStorage |
StorageReference |
ה-StorageReference ששימש ליצירת ה-UploadTask. |
רכיבי ה-event listener של UploadTask מאפשרים לעקוב אחרי אירועי העלאה.
Kotlin
// 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"); } });
טיפול בשינויים במחזור החיים של פעילות
ההעלאות ממשיכות ברקע גם אחרי שינויים במחזור החיים של הפעילות (כמו הצגת תיבת דו-שיח או סיבוב המסך). כל המאזינים שצירפתם יישארו מצורפים. זה עלול לגרום לתוצאות לא צפויות אם הן נקראות אחרי שהפעילות נעצרת.
כדי לפתור את הבעיה הזו, אתם יכולים להירשם למאזינים עם היקף פעילות, כדי לבטל את הרישום שלהם באופן אוטומטי כשהפעילות נפסקת. לאחר מכן, משתמשים ב-method getActiveUploadTasks כשהפעילות מתחילה מחדש כדי לקבל משימות העלאה שעדיין פועלות או שהושלמו לאחרונה.
בדוגמה הבאה אפשר לראות איך עושים את זה, וגם איך לשמור את נתיב ההפניה לאחסון שבו השתמשתם.
Kotlin
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
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
// 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);
הסשנים נמשכים שבוע. אם תנסו להמשיך סשן אחרי שהוא פג או אם הייתה בו שגיאה, תקבלו קריאה חוזרת (callback) של כישלון. באחריותכם לוודא שהקובץ לא השתנה בין ההעלאות.
טיפול בשגיאות
יכולות להיות כמה סיבות לשגיאות בהעלאה, כולל הקובץ המקומי לא קיים, או שלמשתמש אין הרשאה להעלות את הקובץ המיועד. למידע נוסף על שגיאות, ראו טיפול בשגיאות.
דוגמה מלאה
בהמשך מוצגת דוגמה מלאה להעלאה עם מעקב אחרי ההתקדמות וטיפול בשגיאות:
Kotlin
// 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.