Cloud Storage for Firebase, Firebase tarafından sağlanan ve yönetilen bir Cloud Storage paketinden dosyaları hızlı ve kolay bir şekilde indirmenize olanak tanır.
Referans Oluşturma
Bir dosyayı indirmek için önce indirmek istediğiniz dosyaya bir Cloud Storage referansı oluşturun.
Cloud Storage paketinizin köküne alt yollar ekleyerek referans oluşturabilir veya Cloud Storage içindeki bir nesneye referans veren mevcut bir gs:// ya da https:// URL'sinden referans oluşturabilirsiniz.
Kotlin
// Create a storage reference from our app val storageRef = storage.reference // Create a reference with an initial file path and name val pathReference = storageRef.child("images/stars.jpg") // Create a reference to a file from a Google Cloud Storage URI val gsReference = storage.getReferenceFromUrl("gs://bucket/images/stars.jpg") // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! val httpsReference = storage.getReferenceFromUrl( "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg", )
Java
// Create a storage reference from our app StorageReference storageRef = storage.getReference(); // Create a reference with an initial file path and name StorageReference pathReference = storageRef.child("images/stars.jpg"); // Create a reference to a file from a Google Cloud Storage URI StorageReference gsReference = storage.getReferenceFromUrl("gs://bucket/images/stars.jpg"); // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! StorageReference httpsReference = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");
Dosyaları İndir
Referansınız olduğunda getBytes() veya getStream() yöntemini çağırarak Cloud Storage konumundan dosya indirebilirsiniz. Dosyayı başka bir kitaplıkla indirmeyi tercih ederseniz getDownloadUrl() ile indirme URL'si alabilirsiniz.
Bellekte indirme
Dosyayı getBytes() yöntemini kullanarak bir byte[] dosyasına indirin. Bu, dosya indirmenin en kolay yoludur ancak dosyanızın tüm içeriğini belleğe yüklemesi gerekir. Uygulamanızın kullanılabilir belleğinden daha büyük bir dosya isterseniz uygulamanız kilitlenir. Bellek sorunlarına karşı koruma sağlamak için getBytes(), indirilecek maksimum bayt miktarını alır. Maksimum boyutu, uygulamanızın işleyebileceğini bildiğiniz bir değere ayarlayın veya başka bir indirme yöntemi kullanın.
Kotlin
var islandRef = storageRef.child("images/island.jpg") val ONE_MEGABYTE: Long = 1024 * 1024 islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener { // Data for "images/island.jpg" is returned, use this as needed }.addOnFailureListener { // Handle any errors }
Java
StorageReference islandRef = storageRef.child("images/island.jpg"); final long ONE_MEGABYTE = 1024 * 1024; islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() { @Override public void onSuccess(byte[] bytes) { // Data for "images/island.jpg" is returns, use this as needed } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
Yerel bir dosyaya indirme
getFile() yöntemi, dosyayı doğrudan yerel bir cihaza indirir. Kullanıcılarınızın dosyaya çevrimdışıyken erişmesini veya dosyayı farklı bir uygulamada paylaşmasını istiyorsanız bu yöntemi kullanın. getFile(), indirmenizi yönetmek ve indirme durumunu izlemek için kullanabileceğiniz bir DownloadTask döndürür.
Kotlin
islandRef = storageRef.child("images/island.jpg") val localFile = File.createTempFile("images", "jpg") islandRef.getFile(localFile).addOnSuccessListener { // Local temp file has been created }.addOnFailureListener { // Handle any errors }
Java
islandRef = storageRef.child("images/island.jpg"); File localFile = File.createTempFile("images", "jpg"); islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { // Local temp file has been created } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
İndirme işleminizi etkin bir şekilde yönetmek istiyorsanız daha fazla bilgi için İndirmeleri yönetme bölümüne bakın.
URL ile veri indirme
URL'lere dayalı bir indirme altyapınız varsa veya yalnızca paylaşmak istediğiniz bir URL varsa Cloud Storage referansında getDownloadUrl() yöntemini çağırarak bir dosyanın indirme URL'sini alabilirsiniz.
Kotlin
storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener { // Got the download URL for 'users/me/profile.png' }.addOnFailureListener { // Handle any errors }
Java
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { // Got the download URL for 'users/me/profile.png' } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
FirebaseUI ile resim indirme
FirebaseUI, ortak metin kodunu ortadan kaldırmak ve Google'ın en iyi uygulamalarını teşvik etmek için basit, özelleştirilebilir ve üretime hazır yerel mobil bağlamalar sağlar. FirebaseUI'ı kullanarak Glide ile entegrasyonumuz sayesinde Cloud Storage üzerinden resimleri hızlı ve kolay bir şekilde indirebilir, önbelleğe alabilir ve görüntüleyebilirsiniz.
Öncelikle FirebaseUI'ı app/build.gradle uygulamanıza ekleyin:
dependencies { // FirebaseUI Storage only implementation 'com.firebaseui:firebase-ui-storage:9.0.0' }
Ardından, resimleri doğrudan Cloud Storage üzerinden bir ImageView içine yükleyebilirsiniz:
Kotlin
// Reference to an image file in Cloud Storage val storageReference = Firebase.storage.reference // ImageView in your Activity val imageView = findViewById<ImageView>(R.id.imageView) // Download directly from StorageReference using Glide // (See MyAppGlideModule for Loader registration) Glide.with(context) .load(storageReference) .into(imageView)
Java
// Reference to an image file in Cloud Storage StorageReference storageReference = FirebaseStorage.getInstance().getReference(); // ImageView in your Activity ImageView imageView = findViewById(R.id.imageView); // Download directly from StorageReference using Glide // (See MyAppGlideModule for Loader registration) Glide.with(context) .load(storageReference) .into(imageView);
Etkinlik Yaşam Döngüsü Değişikliklerini İşleme
İndirme işlemleri, etkinlik yaşam döngüsü değişikliklerinden (ör. iletişim kutusu gösterme veya ekranı döndürme) sonra bile arka planda devam eder. Eklediğiniz dinleyiciler de ekli kalır. Bu durum, etkinlik durdurulduktan sonra çağrılırlarsa beklenmedik sonuçlara neden olabilir.
Bu sorunu çözmek için dinleyicilerinizi bir etkinlik kapsamına abone ederek etkinlik durduğunda kayıtlarının otomatik olarak iptal edilmesini sağlayabilirsiniz. Ardından, etkinlik yeniden başladığında getActiveDownloadTasks yöntemini kullanarak hâlâ çalışan veya yakın zamanda tamamlanan indirme görevlerini alın.
Aşağıdaki örnekte bu durum gösterilmekte ve kullanılan depolama alanı referans yolunun nasıl kalıcı hale getirileceği de açıklanmaktadır.
Kotlin
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // If there's a download 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 a download in progress, get its reference and create a new StorageReference val stringRef = savedInstanceState.getString("reference") ?: return storageRef = Firebase.storage.getReferenceFromUrl(stringRef) // Find all DownloadTasks under this StorageReference (in this example, there should be one) val tasks = storageRef.activeDownloadTasks if (tasks.size > 0) { // Get the task monitoring the download 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 a download 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 a download 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 DownloadTasks under this StorageReference (in this example, there should be one) List<FileDownloadTask> tasks = mStorageRef.getActiveDownloadTasks(); if (tasks.size() > 0) { // Get the task monitoring the download FileDownloadTask task = tasks.get(0); // Add new listeners to the task using an Activity scope task.addOnSuccessListener(this, new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot state) { // Success! // ... } }); } }
Hataları işleme
İndirme sırasında hata oluşmasının çeşitli nedenleri olabilir. Örneğin, dosya mevcut olmayabilir veya kullanıcının istenen dosyaya erişim izni olmayabilir. Hatalar hakkında daha fazla bilgiyi belgelerin Hataları İşleme bölümünde bulabilirsiniz.
Tam Örnek
Hata işleme ile indirme işleminin tam bir örneği aşağıda gösterilmiştir:
Kotlin
storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener { // Use the bytes to display the image }.addOnFailureListener { // Handle any errors }
Java
storageRef.child("users/me/profile.png").getBytes(Long.MAX_VALUE).addOnSuccessListener(new OnSuccessListener<byte[]>() { @Override public void onSuccess(byte[] bytes) { // Use the bytes to display the image } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
Cloud Storage içinde depolanan dosyaların meta verilerini alabilir ve güncelleyebilirsiniz.