שימוש במטא-נתונים של קבצים ב-Cloud Storage ב-Android
קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
אחרי שמעלים קובץ לCloud Storage, אפשר גם לקבל ולעדכן את המטא-נתונים של הקובץ, למשל כדי לראות או לעדכן את סוג התוכן.
בקבצים אפשר גם לאחסן צמדי מפתח/ערך בהתאמה אישית עם מטא-נתונים נוספים של הקובץ.
אחזור מטא-נתונים של קובץ
המטא-נתונים של הקובץ מכילים מאפיינים נפוצים כמו name, size ו-contentType (שנקרא לעיתים קרובות סוג MIME), בנוסף למאפיינים פחות נפוצים כמו contentDisposition ו-timeCreated. אפשר לאחזר את המטא-נתונים האלה מהפניה Cloud Storage באמצעות השיטה getMetadata().
Kotlin
// Create a storage reference from our appvalstorageRef=storage.reference// Get reference to the filevalforestRef=storageRef.child("images/forest.jpg")
forestRef.metadata.addOnSuccessListener{metadata->
// Metadata now contains the metadata for 'images/forest.jpg'}.addOnFailureListener{// Uh-oh, an error occurred!}
// Create a storage reference from our appStorageReferencestorageRef=storage.getReference();// Get reference to the fileStorageReferenceforestRef=storageRef.child("images/forest.jpg");
forestRef.getMetadata().addOnSuccessListener(newOnSuccessListener<StorageMetadata>(){@OverridepublicvoidonSuccess(StorageMetadatastorageMetadata){// Metadata now contains the metadata for 'images/forest.jpg'}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptionexception){// Uh-oh, an error occurred!}});
אפשר לעדכן את המטא-נתונים של הקובץ בכל שלב אחרי שההעלאה של הקובץ מסתיימת באמצעות השיטה updateMetadata(). למידע נוסף על המאפיינים שאפשר לעדכן, אפשר לעיין ברשימה המלאה. רק המאפיינים שצוינו במטא-נתונים מתעדכנים,
כל השאר נשארים ללא שינוי.
Kotlin
// Create a storage reference from our appvalstorageRef=storage.reference// Get reference to the filevalforestRef=storageRef.child("images/forest.jpg")
// Create file metadata including the content typevalmetadata=storageMetadata{contentType="image/jpg"setCustomMetadata("myCustomProperty","myValue")}// Update metadata propertiesforestRef.updateMetadata(metadata).addOnSuccessListener{updatedMetadata->
// Updated metadata is in updatedMetadata}.addOnFailureListener{// Uh-oh, an error occurred!}
// Create a storage reference from our appStorageReferencestorageRef=storage.getReference();// Get reference to the fileStorageReferenceforestRef=storageRef.child("images/forest.jpg");
// Create file metadata including the content typeStorageMetadatametadata=newStorageMetadata.Builder().setContentType("image/jpg").setCustomMetadata("myCustomProperty","myValue").build();// Update metadata propertiesforestRef.updateMetadata(metadata).addOnSuccessListener(newOnSuccessListener<StorageMetadata>(){@OverridepublicvoidonSuccess(StorageMetadatastorageMetadata){// Updated metadata is in storageMetadata}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptionexception){// Uh-oh, an error occurred!}});
כדי למחוק מאפייני מטא-נתונים שאפשר לכתוב בהם, מעבירים את הערך null:
Kotlin
// Create file metadata with property to deletevalmetadata=storageMetadata{contentType=null}// Delete the metadata propertyforestRef.updateMetadata(metadata).addOnSuccessListener{updatedMetadata->
// updatedMetadata.contentType should be null}.addOnFailureListener{// Uh-oh, an error occurred!}
// Create file metadata with property to deleteStorageMetadatametadata=newStorageMetadata.Builder().setContentType(null).build();// Delete the metadata propertyforestRef.updateMetadata(metadata).addOnSuccessListener(newOnSuccessListener<StorageMetadata>(){@OverridepublicvoidonSuccess(StorageMetadatastorageMetadata){// metadata.contentType should be null}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptionexception){// Uh-oh, an error occurred!}});
יכולות להיות כמה סיבות לשגיאות שמתרחשות כשמקבלים או מעדכנים מטא-נתונים, כולל קובץ שלא קיים או משתמש שאין לו הרשאה לגשת לקובץ הרצוי. מידע נוסף על שגיאות זמין בקטע Handle Errors במסמכים.
מטא-נתונים בהתאמה אישית
אפשר לציין מטא נתונים בהתאמה אישית באמצעות ה-method setCustomMetadata() במחלקה StorageMetadata.Builder.
Kotlin
valmetadata=storageMetadata{setCustomMetadata("location","Yosemite, CA, USA")setCustomMetadata("activity","Hiking")}
אפשר לאחסן נתונים ספציפיים לאפליקציה לכל קובץ במטא-נתונים בהתאמה אישית, אבל מומלץ מאוד להשתמש במסד נתונים (כמו Firebase Realtime Database) כדי לאחסן ולסנכרן את סוג הנתונים הזה.
מאפייני המטא-נתונים של הקובץ
בהמשך מופיעה רשימה מלאה של מאפייני המטא-נתונים בקובץ:
Property Getter
סוג
הפונקציה להגדרת ערך קיימת
getBucket
String
לא
getGeneration
String
לא
getMetadataGeneration
String
לא
getPath
String
לא
getName
String
לא
getSizeBytes
long
לא
getCreationTimeMillis
long
לא
getUpdatedTimeMillis
long
לא
getMd5Hash
String
לא
getCacheControl
String
כן
getContentDisposition
String
כן
getContentEncoding
String
כן
getContentLanguage
String
כן
getContentType
String
כן
getCustomMetadata
String
כן
getCustomMetadataKeys
Set<String>
לא
העלאה, הורדה ועדכון של קבצים הם חשובים, אבל חשוב גם להיות מסוגלים להסיר אותם. במאמר הזה נסביר איך למחוק קבצים מ-Cloud Storage.
[[["התוכן קל להבנה","easyToUnderstand","thumb-up"],["התוכן עזר לי לפתור בעיה","solvedMyProblem","thumb-up"],["סיבה אחרת","otherUp","thumb-up"]],[["חסרים לי מידע או פרטים","missingTheInformationINeed","thumb-down"],["התוכן מורכב מדי או עם יותר מדי שלבים","tooComplicatedTooManySteps","thumb-down"],["התוכן לא עדכני","outOfDate","thumb-down"],["בעיה בתרגום","translationIssue","thumb-down"],["בעיה בדוגמאות/בקוד","samplesCodeIssue","thumb-down"],["סיבה אחרת","otherDown","thumb-down"]],["עדכון אחרון: 2025-09-05 (שעון UTC)."],[],[],null,["\u003cbr /\u003e\n\nAfter uploading a file to Cloud Storage reference, you can also get\nand update the file metadata, for example to view or update the content type.\nFiles can also store custom key/value pairs with additional file metadata.\n| **Note:** By default, a Cloud Storage for Firebase bucket requires Firebase Authentication to perform any action on the bucket's data or files. You can change your Firebase Security Rules for Cloud Storage to [allow unauthenticated access for specific situations](/docs/storage/security/rules-conditions#public). However, for most situations, we strongly recommend [restricting access and setting up robust security rules](/docs/storage/security/get-started) (especially for production apps). Note that if you use Google App Engine and have a default Cloud Storage bucket with a name format of `*.appspot.com`, you may need to consider [how your security rules impact access to App Engine files](/docs/storage/gcp-integration#security-rules-and-app-engine-files).\n\nGet File Metadata\n\nFile metadata contains common properties such as `name`, `size`, and\n`contentType` (often referred to as MIME type) in addition to some less\ncommon ones like `contentDisposition` and `timeCreated`. This metadata can be\nretrieved from a Cloud Storage reference using\nthe `getMetadata()` method. \n\nKotlin \n\n```kotlin\n// Create a storage reference from our app\nval storageRef = storage.reference\n\n// Get reference to the file\nval forestRef = storageRef.child(\"images/forest.jpg\")\n``` \n\n```kotlin\nforestRef.metadata.addOnSuccessListener { metadata -\u003e\n // Metadata now contains the metadata for 'images/forest.jpg'\n}.addOnFailureListener {\n // Uh-oh, an error occurred!\n}https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt#L345-L349\n```\n\nJava \n\n```java\n// Create a storage reference from our app\nStorageReference storageRef = storage.getReference();\n\n// Get reference to the file\nStorageReference forestRef = storageRef.child(\"images/forest.jpg\");\n``` \n\n```java\nforestRef.getMetadata().addOnSuccessListener(new OnSuccessListener\u003cStorageMetadata\u003e() {\n @Override\n public void onSuccess(StorageMetadata storageMetadata) {\n // Metadata now contains the metadata for 'images/forest.jpg'\n }\n}).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception exception) {\n // Uh-oh, an error occurred!\n }\n});https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/StorageActivity.java#L437-L447\n```\n\nUpdate File Metadata\n\nYou can update file metadata at any time after the file upload completes by\nusing the `updateMetadata()` method. Refer to the\n[full list](#file-metadata-properties) for more information on what properties\ncan be updated. Only the properties specified in the metadata are updated,\nall others are left unmodified. \n\nKotlin \n\n```kotlin\n// Create a storage reference from our app\nval storageRef = storage.reference\n\n// Get reference to the file\nval forestRef = storageRef.child(\"images/forest.jpg\")\n``` \n\n```kotlin\n// Create file metadata including the content type\nval metadata = storageMetadata {\n contentType = \"image/jpg\"\n setCustomMetadata(\"myCustomProperty\", \"myValue\")\n}\n\n// Update metadata properties\nforestRef.updateMetadata(metadata).addOnSuccessListener { updatedMetadata -\u003e\n // Updated metadata is in updatedMetadata\n}.addOnFailureListener {\n // Uh-oh, an error occurred!\n}https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt#L353-L364\n```\n\nJava \n\n```java\n// Create a storage reference from our app\nStorageReference storageRef = storage.getReference();\n\n// Get reference to the file\nStorageReference forestRef = storageRef.child(\"images/forest.jpg\");\n``` \n\n```java\n// Create file metadata including the content type\nStorageMetadata metadata = new StorageMetadata.Builder()\n .setContentType(\"image/jpg\")\n .setCustomMetadata(\"myCustomProperty\", \"myValue\")\n .build();\n\n// Update metadata properties\nforestRef.updateMetadata(metadata)\n .addOnSuccessListener(new OnSuccessListener\u003cStorageMetadata\u003e() {\n @Override\n public void onSuccess(StorageMetadata storageMetadata) {\n // Updated metadata is in storageMetadata\n }\n })\n .addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception exception) {\n // Uh-oh, an error occurred!\n }\n });https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/StorageActivity.java#L451-L470\n```\n\nYou can delete writable metadata properties by passing `null`: \n\nKotlin \n\n```kotlin\n// Create file metadata with property to delete\nval metadata = storageMetadata {\n contentType = null\n}\n\n// Delete the metadata property\nforestRef.updateMetadata(metadata).addOnSuccessListener { updatedMetadata -\u003e\n // updatedMetadata.contentType should be null\n}.addOnFailureListener {\n // Uh-oh, an error occurred!\n}https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt#L374-L384\n```\n\nJava \n\n```java\n// Create file metadata with property to delete\nStorageMetadata metadata = new StorageMetadata.Builder()\n .setContentType(null)\n .build();\n\n// Delete the metadata property\nforestRef.updateMetadata(metadata)\n .addOnSuccessListener(new OnSuccessListener\u003cStorageMetadata\u003e() {\n @Override\n public void onSuccess(StorageMetadata storageMetadata) {\n // metadata.contentType should be null\n }\n })\n .addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception exception) {\n // Uh-oh, an error occurred!\n }\n });https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/StorageActivity.java#L480-L498\n```\n\nHandle Errors\n\nThere are a number of reasons why errors may occur on getting or updating\nmetadata, including the file not existing, or the user not having permission\nto access the desired file. More information on errors can be found in the\n[Handle Errors](/docs/storage/android/handle-errors)\nsection of the docs.\n\nCustom Metadata\n\nYou can specify custom metadata using the `setCustomMetadata()` method in the\n`StorageMetadata.Builder` class. \n\nKotlin \n\n```kotlin\nval metadata = storageMetadata {\n setCustomMetadata(\"location\", \"Yosemite, CA, USA\")\n setCustomMetadata(\"activity\", \"Hiking\")\n}https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt#L390-L393\n```\n\nJava \n\n```java\nStorageMetadata metadata = new StorageMetadata.Builder()\n .setCustomMetadata(\"location\", \"Yosemite, CA, USA\")\n .setCustomMetadata(\"activity\", \"Hiking\")\n .build();https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/storage/app/src/main/java/com/google/firebase/referencecode/storage/StorageActivity.java#L504-L507\n```\n\nYou can store app-specific data for each file in custom metadata, but we highly\nrecommend using a database (such as the\n[Firebase Realtime Database](/docs/database/android/start))\nto store and synchronize this type of data.\n\nFile Metadata Properties\n\nA full list of metadata properties on a file is available below:\n\n| Property Getter | Type | Setter Exists |\n|-------------------------|---------------|---------------|\n| `getBucket` | `String` | NO |\n| `getGeneration` | `String` | NO |\n| `getMetadataGeneration` | `String` | NO |\n| `getPath` | `String` | NO |\n| `getName` | `String` | NO |\n| `getSizeBytes` | `long` | NO |\n| `getCreationTimeMillis` | `long` | NO |\n| `getUpdatedTimeMillis` | `long` | NO |\n| `getMd5Hash` | `String` | NO |\n| `getCacheControl` | `String` | YES |\n| `getContentDisposition` | `String` | YES |\n| `getContentEncoding` | `String` | YES |\n| `getContentLanguage` | `String` | YES |\n| `getContentType` | `String` | YES |\n| `getCustomMetadata` | `String` | YES |\n| `getCustomMetadataKeys` | `Set\u003cString\u003e` | NO |\n\nUploading, downloading, and updating files is important, but so is being able\nto remove them. Let's learn how to\n[delete files](/docs/storage/android/delete-files)\nfrom Cloud Storage."]]