Cloud Storage dla Firebase umożliwia szybkie i łatwe pobieranie plików z zasobnika Cloud Storage udostępnianego i zarządzanego przez Firebase.
Utwórz odniesienie
Aby pobrać plik, najpierw utwórz odniesienie do Cloud Storage dla pliku, który chcesz pobrać.
Możesz utworzyć odniesienie, dołączając ścieżki podrzędne do katalogu głównego zasobnika Cloud Storage lub możesz utworzyć odniesienie z istniejącego adresu URL gs://
lub https://
odnoszącego się do obiektu w Cloud Storage.
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");
Pobierz pliki
Gdy już uzyskasz referencje, 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()
.
Pobierz w pamięci
Pobierz plik do byte[]
za pomocą metody getBytes()
. Jest to najłatwiejszy sposób pobrania pliku, ale wymaga załadowania całej zawartości pliku do pamięci. Jeśli poprosisz o plik większy niż dostępna pamięć aplikacji, aplikacja ulegnie awarii. Aby zabezpieczyć się przed problemami z pamięcią, getBytes()
pobiera maksymalną liczbę bajtów. Ustaw maksymalny rozmiar na taki, jaki obsługuje Twoja aplikacja, lub użyj innej metody pobierania.
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 } });
Pobierz 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ć plik w innej aplikacji. getFile()
zwraca DownloadTask
, której możesz użyć do zarządzania pobieraniem i monitorowania statusu pobierania.
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 } });
Jeśli chcesz aktywnie zarządzać pobieraniem, zobacz Zarządzanie pobieraniem , aby uzyskać więcej informacji.
Pobierz dane poprzez adres 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()
w odniesieniu do Cloud Storage.
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 } });
Pobieranie obrazów za pomocą FirebaseUI
FirebaseUI zapewnia proste, konfigurowalne i gotowe do produkcji natywne powiązania mobilne, które pozwalają wyeliminować szablonowy kod i promować najlepsze praktyki Google. Korzystając z FirebaseUI, możesz szybko i łatwo pobierać, buforować i wyświetlać obrazy z Cloud Storage, korzystając z naszej integracji z Glide .
Najpierw dodaj FirebaseUI do swojej app/build.gradle
:
dependencies { // FirebaseUI Storage only implementation 'com.firebaseui:firebase-ui-storage:7.2.0' }
Następnie możesz załadować obrazy bezpośrednio z Cloud Storage do ImageView
:
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);
Obsługuj zmiany w cyklu życia działania
Pobieranie jest kontynuowane w tle nawet po zmianie cyklu życia aktywności (takiej jak wyświetlenie okna dialogowego lub obrócenie ekranu). Wszyscy przypisani słuchacze również pozostaną dołączeni. Może to spowodować nieoczekiwane wyniki, jeśli zostaną wywołane po zatrzymaniu działania.
Możesz rozwiązać ten problem, subskrybując słuchaczy z zakresem aktywności, aby automatycznie wyrejestrowywać ich po zakończeniu aktywności. Następnie użyj metody getActiveDownloadTasks
po ponownym uruchomieniu działania, aby uzyskać zadania pobierania, które nadal działają lub zostały niedawno zakończone.
Poniższy przykład ilustruje to, a także pokazuje, jak zachować używaną ścieżkę referencyjną magazynu.
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! // ... } }); } }
Obsługa błędów
Istnieje wiele powodów, dla których mogą wystąpić błędy podczas pobierania, na przykład nieistniejący plik lub brak uprawnień dostępu użytkownika do żądanego pliku. Więcej informacji na temat błędów można znaleźć w sekcji Obsługiwanie błędów w dokumentacji.
Pełny przykład
Pełny przykład pobierania z obsługą błędów pokazano poniżej:
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 } });
Możesz także pobierać i aktualizować metadane plików przechowywanych w Cloud Storage.