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 Storageodwołanie do pliku, który chcesz pobrać.
Możesz utworzyć odwołanie, dołączając ścieżki podrzędne do katalogu głównego Cloud Storage zasobnika, lub utworzyć odwołanie z istniejącego adresu URL gs://
lub https://
, który odwołuje 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 uzyskasz odniesienie, możesz pobrać pliki z Cloud Storage, wywołując funkcję getBytes()
lub getStream()
. Jeśli wolisz pobrać plik za pomocą innej biblioteki, możesz uzyskać adres URL pobierania za pomocą getDownloadUrl()
.
Pobieranie w pamięci
Pobierz plik na byte[]
za pomocą metody getBytes()
. Jest to najprostszy sposób pobierania pliku, ale wymaga załadowania całej zawartości pliku do pamięci. Jeśli zażądasz pliku większego 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ść, z którą Twoja aplikacja sobie poradzi, 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 chcą mieć dostęp do pliku offline lub udostępnić go w innej aplikacji. Funkcja getFile()
zwraca obiekt DownloadTask
, którego możesz użyć do zarządzania pobieraniem i monitorowania jego stanu.
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, więcej informacji znajdziesz w sekcji 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 udostępnia proste, konfigurowalne i gotowe do wdrożenia w środowisku produkcyjnym natywne powiązania mobilne, które eliminują kod standardowy 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 wczytać 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 zmianie cyklu życia aktywności (np. po wyświetleniu okna lub obróceniu ekranu). Wszyscy słuchacze, którzy byli wcześniej połączeni, pozostaną połączeni. Jeśli zostaną wywołane po zatrzymaniu aktywności, może to spowodować nieoczekiwane wyniki.
Możesz rozwiązać ten problem, subskrybując odbiorców z zakresem aktywności, aby automatycznie wyrejestrowywać ich po zakończeniu aktywności. Następnie użyj metody getActiveDownloadTasks
, gdy aktywność zostanie ponownie uruchomiona, aby uzyskać zadania pobierania, które są nadal uruchomione lub zostały niedawno zakończone.
Przykład poniżej pokazuje, jak to zrobić, a także jak zachować używaną ścieżkę odniesienia 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 pobierania mogą wystąpić z różnych powodów, np. z powodu braku pliku lub braku uprawnień użytkownika do uzyskania dostępu do wybranego pliku. Więcej informacji o błędach znajdziesz w sekcji Obsługa błędów w dokumentacji.
Pełny przykład
Pełny przykład pobierania z obsługą błędów znajdziesz poniżej:
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.