Cloud Storage for Firebase umożliwia szybkie i łatwe pobieranie plików z zasobnika Cloud Storage udostępnianego i zarządzanego przez Firebase.
Tworzenie referencji
Aby pobrać plik, najpierw utwórz Cloud Storageplik referencyjny do pliku, który chcesz pobrać.
Możesz utworzyć odwołanie, dołączając ścieżki podrzędne do katalogu głównego zasobnika Cloud Storage, lub utworzyć odwołanie z 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 pobrać 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().
Pobierz 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 opcji, jeśli użytkownicy chcą mieć dostęp do pliku w trybie offline lub udostępnić go w innej aplikacji. getFile() zwraca DownloadTask, którego możesz użyć do zarządzania pobieraniem i monitorowania stanu pobierania.
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, zapoznaj się z artykułem Zarządzanie pobieraniem.
Pobieranie danych za pomocą adresu URL
Jeśli masz już infrastrukturę pobierania opartą na adresach URL lub chcesz udostępnić adres URL, możesz uzyskać adres URL pobierania pliku, wywołując metodę getDownloadUrl() w odwołaniu 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 wykorzystania 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ć, zapisywać w pamięci podręcznej i wyświetlać obrazy z Cloud Storage, korzystając z naszej integracji z Glide.
Najpierw dodaj FirebaseUI do pliku 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 cyklu życia aktywności
Pobieranie jest kontynuowane w tle nawet po zmianie cyklu życia działania (np. po wyświetleniu okna lub obróceniu ekranu). Wszystkie dołączone detektory również pozostaną dołączone. Może to spowodować nieoczekiwane wyniki, jeśli zostaną wywołane po zatrzymaniu aktywności.
Możesz rozwiązać ten problem, subskrybując detektory z zakresem aktywności, aby automatycznie wyrejestrowywać je po zakończeniu aktywności. Następnie użyj metody getActiveDownloadTasks, gdy aktywność zostanie ponownie uruchomiona, aby uzyskać zadania pobierania, które nadal są wykonywane lub zostały niedawno ukończone.
Przykład poniżej pokazuje, jak to zrobić, a także jak zachować użytą ścieżkę do pliku referencyjnego w pamięci masowej.
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ługuj błędy
Podczas pobierania mogą wystąpić błędy z różnych powodów, np. plik nie istnieje lub użytkownik nie ma uprawnień 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.