Cloud Storage for Firebase, Firebase tarafından sağlanan ve yönetilen bir Cloud Storage paketinden hızlı ve kolay bir şekilde dosya indirmenize olanak tanır.
Referans Oluşturma
Dosya indirmek için önce indirmek istediğiniz dosyaya ait bir Cloud Storage referansı oluşturun.
Cloud Storage paketinizin köküne alt yollar ekleyerek veya Cloud Storage'da bir nesneye referans veren mevcut bir gs://
ya da https://
URL'sinden referans oluşturabilirsiniz.
Kotlin+KTX
// 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 edindikten sonra getBytes()
veya getStream()
yöntemini çağırarak dosyaları Cloud Storage'dan indirebilirsiniz. Dosyayı başka bir kitaplıkla indirmeyi tercih ederseniz getDownloadUrl()
ile bir indirme URL'si alabilirsiniz.
Bellekte indir
Dosyayı, getBytes()
yöntemini kullanarak bir byte[]
konumuna indirin. Bu, bir dosyayı indirmenin en kolay yoludur ancak dosyanızın tüm içeriğini belleğe yüklemelidir. Uygulamanızın kullanılabilir belleğinden daha büyük bir dosya isteğinde bulunursanız uygulamanız kilitlenir. Bellek sorunlarına karşı koruma sağlamak için getBytes()
, indirilebilecek maksimum bayt miktarını belirler. Maksimum boyutu, uygulamanızın işleyebildiğini bildiğiniz
bir şeye ayarlayın veya başka bir indirme yöntemi kullanın.
Kotlin+KTX
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 dosyaya indir
getFile()
yöntemi, dosyayı doğrudan yerel bir cihaza indirir. Kullanıcılarınız çevrimdışıyken dosyaya erişmek veya dosyayı farklı bir uygulamada paylaşmak
istediğinde bunu kullanın. getFile()
, indirme işleminizi yönetmek ve indirme durumunu izlemek için
kullanabileceğiniz bir DownloadTask
döndürür.
Kotlin+KTX
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 İndirilenleri Yönetme bölümünü inceleyin.
Verileri URL Yoluyla İndir
URL'leri temel alan bir indirme altyapınız varsa veya yalnızca bir URL'nin paylaşılmasını istiyorsanız Cloud Storage referansında getDownloadUrl()
yöntemini çağırarak dosyanın indirme URL'sini alabilirsiniz.
Kotlin+KTX
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 İndirme
FirebaseUI, ortak koddan kurtulmak ve Google en iyi uygulamalarını desteklemek için basit, özelleştirilebilir ve üretime hazır yerel mobil bağlamalar sunar. FirebaseUI ile Glide entegrasyonumuzu kullanarak Cloud Storage'dan görüntüleri hızlı ve kolay bir şekilde indirebilir, önbelleğe alabilir ve görüntüleyebilirsiniz.
İlk olarak FirebaseUI'yi app/build.gradle
sayfanıza ekleyin:
dependencies { // FirebaseUI Storage only implementation 'com.firebaseui:firebase-ui-storage:7.2.0' }
Ardından, görüntüleri doğrudan Cloud Storage'dan bir ImageView
hizmetine yükleyebilirsiniz:
Kotlin+KTX
// 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 Yönetme
İ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 bağlı kalmaya devam eder. Bu durum, etkinlik durdurulduktan sonra çağrılırsa beklenmedik sonuçlara neden olabilir.
Bu sorunu, etkinlik durduğunda kaydı otomatik olarak iptal etmeleri için dinleyicilerinize etkinlik kapsamıyla abone yaparak çözebilirsiniz. Ardından, hâlâ çalışmakta olan veya yakın zamanda tamamlanan indirme görevlerini almak için etkinlik yeniden başlatıldığında getActiveDownloadTasks
yöntemini kullanın.
Aşağıdaki örnekte bu durum gösterilmekte ve kullanılan depolama alanı referans yolunun nasıl korunacağı da gösterilmektedir.
Kotlin+KTX
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ı Giderme
İndirme sırasında, dosyanın mevcut olmaması veya kullanıcının istenen dosyaya erişim izni olmaması gibi çeşitli nedenler vardır. Hatalar hakkında daha fazla bilgiyi belgelerin İşleyici Hataları bölümünde bulabilirsiniz.
Tam Örnek
Hata işleme kullanılan bir indirme örneği aşağıda verilmiştir:
Kotlin+KTX
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'da depolanan dosyalar için meta verileri de alabilir ve güncelleyebilirsiniz.