How to download a file from Firebase Storage to the External_Storage of Android
private void downloadFile() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("<your_bucket>");
StorageReference islandRef = storageRef.child("file.txt");
File rootPath = new File(Environment.getExternalStorageDirectory(), "file_name");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,"imageName.txt");
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("firebase ",";local tem file created created " +localFile.toString());
// updateDb(timestamp,localFile.toString(),position);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Log.e("firebase ",";local tem file not created created " +exception.toString());
}
});
}
MainActivity.java
Button button=findViewById(R.id.download);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
downloadfile();
}
});
}
private void downloadfile() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/imagestore-b2432.appspot.com/o/Nature.jpg?alt=media&token=07d95162-45f8-424e-9658-8f9022485930");
ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Nature.jpg");
pd.setMessage("Downloading Please Wait!");
pd.setIndeterminate(true);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
final File rootPath = new File(Environment.getExternalStorageDirectory(), "MADBO DOWNLOADS");
if (!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath, "Nature.jpg");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener <FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("firebase ", ";local tem file created created " + localFile.toString());
if (!isVisible()){
return;
}
if (localFile.canRead()){
pd.dismiss();
}
Toast.makeText(this, "Download Completed", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Internal storage/MADBO/Nature.jpg", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Log.e("firebase ", ";local tem file not created created " + exception.toString());
Toast.makeText(this, "Download Incompleted", Toast.LENGTH_LONG).show();
}
});
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>