Cloud Storage for Firebase umożliwia szybkie i łatwe pobieranie plików z Cloud Storage zasobnika udostępnianego i zarządzanego przez Firebase.
Tworzenie referencji
Aby pobrać plik, najpierw utwórz Cloud Storage referencję do pliku, który chcesz pobrać.
Referencję możesz utworzyć, dołączając ścieżki podrzędne do katalogu głównego zasobnika
Cloud Storage, lub tworząc referencję na podstawie istniejącego adresu URL
gs:// lub https:// odwołującego się do obiektu w Cloud Storage.
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");
Pobieranie plików
Gdy masz już referencję, możesz pobierać pliki z Cloud Storage
wywołując getBytes() lub getStream(). Jeśli wolisz pobrać plik za pomocą innej biblioteki, możesz uzyskać adres URL pobierania za pomocą getDownloadUrl().
Pobieranie do pamięci
Pobierz plik do byte[] za pomocą metody getBytes(). Jest to najprostszy sposób pobierania pliku, ale wymaga wczytania całej zawartości pliku do pamięci. Jeśli poprosisz o plik większy niż dostępna pamięć aplikacji, aplikacja ulegnie awarii. Aby zapobiec problemom z pamięcią, getBytes() pobiera maksymalną liczbę bajtów. Ustaw maksymalny rozmiar na wartość, którą Twoja aplikacja może obsłużyć, lub użyj innej metody pobierania.
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 } });
Pobieranie do pliku lokalnego
Metoda getFile() pobiera plik bezpośrednio na urządzenie lokalne. Użyj tej metody, jeśli użytkownicy mają mieć dostęp do pliku offline lub udostępniać go w innej aplikacji. getFile() zwraca DownloadTask, za pomocą którego możesz zarządzać pobieraniem i monitorować jego stan.
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 } });
Jeśli chcesz aktywnie zarządzać pobieraniem, przeczytaj artykuł Zarządzanie pobieraniem.
Pobieranie danych za pomocą adresu URL
Jeśli masz już infrastrukturę pobierania opartą na adresach URL lub po prostu chcesz
udostępnić adres URL, możesz uzyskać adres URL pobierania pliku, wywołując metodę
getDownloadUrl() na referencji Cloud Storage.
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 } });
Pobieranie obrazów za pomocą FirebaseUI
FirebaseUI zapewnia proste, konfigurowalne i gotowe do użycia w środowisku produkcyjnym natywne powiązania mobilne, które eliminują powtarzalny kod i promują sprawdzone metody Google. Za pomocą FirebaseUI możesz szybko i łatwo pobierać, buforować i wyświetlać obrazy z Cloud Storage dzięki integracji z Glide.
Najpierw dodaj FirebaseUI do app/build.gradle:
dependencies { // FirebaseUI Storage only implementation 'com.firebaseui:firebase-ui-storage:9.0.0' }
Następnie możesz wczytywać obrazy bezpośrednio z Cloud Storage do ImageView:
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);
Obsługa zmian w cyklu życia aktywności
Pobieranie jest kontynuowane w tle nawet po zmianach w cyklu życia aktywności (np. po wyświetleniu okna lub obróceniu ekranu). Wszystkie dołączone detektory pozostaną dołączone. Jeśli zostaną wywołane po zatrzymaniu aktywności, może to spowodować nieoczekiwane wyniki.
Możesz rozwiązać ten problem, subskrybując detektory w zakresie aktywności, aby automatycznie je wyrejestrować po zatrzymaniu aktywności. Następnie, gdy aktywność zostanie ponownie uruchomiona, użyj metody getActiveDownloadTasks, aby uzyskać zadania pobierania, które są nadal wykonywane lub zostały niedawno zakończone.
Poniższy przykład pokazuje, jak to zrobić, a także jak utrwalić ścieżkę referencji do pamięci.
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! // ... } }); } }
Obsługa błędów
Błędy podczas pobierania mogą wystąpić z wielu powodów, m.in. z powodu braku pliku lub braku uprawnień użytkownika do dostępu do żądanego pliku. Więcej informacji o błędach znajdziesz w sekcji Obsługa błędów w dokumentacji.
Pełny przykład
Poniżej znajdziesz pełny przykład pobierania z obsługą błędów:
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 } });
Możesz też pobierać i aktualizować metadane plików przechowywanych w Cloud Storage.