Cloud Storage for Firebase ti consente di scaricare file in modo facile e veloce da un bucket Cloud Storage fornito e gestito da Firebase.
Crea un riferimento
Per scaricare un file, crea innanzitutto un riferimento Cloud Storage al file che desideri scaricare.
Puoi creare un riferimento aggiungendo percorsi secondari alla radice del tuo bucket Cloud Storage oppure puoi creare un riferimento da un URL gs://
o https://
esistente che fa riferimento a un oggetto in 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");
Scaricare files
Una volta ottenuto un riferimento, puoi scaricare i file da Cloud Storage chiamando getBytes()
o getStream()
. Se preferisci scaricare il file con un'altra libreria, puoi ottenere un URL di download con getDownloadUrl()
.
Scarica in memoria
Scarica il file in un byte[]
con il metodo getBytes()
. Questo è il modo più semplice per scaricare un file, ma deve caricare in memoria l'intero contenuto del file. Se richiedi un file più grande della memoria disponibile dell'app, l'app andrà in crash. Per proteggersi da problemi di memoria, getBytes()
richiede una quantità massima di byte da scaricare. Imposta la dimensione massima su qualcosa che sai che la tua app può gestire o utilizza un altro metodo di download.
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 } });
Scarica in un file locale
Il metodo getFile()
scarica un file direttamente su un dispositivo locale. Utilizza questa opzione se i tuoi utenti desiderano avere accesso al file offline o condividere il file in un'altra app. getFile()
restituisce un DownloadTask
che puoi usare per gestire il tuo download e monitorare lo stato del download.
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 } });
Se desideri gestire attivamente il tuo download, consulta Gestire i download per ulteriori informazioni.
Scarica dati tramite URL
Se disponi già di un'infrastruttura di download basata sugli URL o vuoi semplicemente condividere un URL, puoi ottenere l'URL di download di un file chiamando il metodo getDownloadUrl()
su un riferimento 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 } });
Download di immagini con FirebaseUI
FirebaseUI fornisce associazioni mobili native semplici, personalizzabili e pronte per la produzione per eliminare il codice boilerplate e promuovere le best practice di Google. Utilizzando FirebaseUI puoi scaricare, memorizzare nella cache e visualizzare immagini da Cloud Storage in modo rapido e semplice utilizzando la nostra integrazione con Glide .
Innanzitutto, aggiungi FirebaseUI alla tua app/build.gradle
:
dependencies { // FirebaseUI Storage only implementation 'com.firebaseui:firebase-ui-storage:7.2.0' }
Quindi puoi caricare le immagini direttamente da Cloud Storage in un 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);
Gestire le modifiche del ciclo di vita delle attività
I download continuano in background anche dopo le modifiche al ciclo di vita dell'attività (come la presentazione di una finestra di dialogo o la rotazione dello schermo). Tutti gli ascoltatori che avevi collegato rimarranno anch'essi collegati. Ciò potrebbe causare risultati imprevisti se vengono chiamati dopo che l'attività è stata interrotta.
Puoi risolvere questo problema iscrivendo i tuoi ascoltatori con un ambito di attività per annullarne automaticamente la registrazione quando l'attività si interrompe. Utilizzare quindi il metodo getActiveDownloadTasks
quando l'attività viene riavviata per ottenere le attività di download ancora in esecuzione o completate di recente.
L'esempio seguente lo dimostra e mostra anche come rendere persistente il percorso di riferimento di archiviazione utilizzato.
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! // ... } }); } }
Gestire gli errori
Esistono diversi motivi per cui possono verificarsi errori durante il download, incluso il file non esistente o l'utente che non dispone dell'autorizzazione per accedere al file desiderato. Ulteriori informazioni sugli errori sono disponibili nella sezione Gestione degli errori dei documenti.
Esempio completo
Di seguito è riportato un esempio completo di download con gestione degli errori:
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 } });
Puoi anche ottenere e aggiornare i metadati per i file archiviati in Cloud Storage.