How to download file from Firebase storage to custom folder? - android

I have been searching all day long even here on stack overflow but none of the code seems to work. I want to download a file(s) from FirebaseStorage to a custom folder on internal/external storage but no luck whatsoever.
my code:
private void downloadfile() {
mStorageRef = FirebaseStorage.getInstance().getReference();
ref = mStorageRef.child("song.mp3");
try {
File localFile = File.createTempFile("song", "mp3");
} catch (IOException e) {
e.printStackTrace();
}
File storagePath = new File(Environment.getExternalStorageDirectory(), "My Folder");
// Create direcorty if not exists
if(!storagePath.exists()) {
storagePath.mkdirs();
}
final File myFile = new File(storagePath,"song.mp3");
mStorageRef.getFile(myFile).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
}
});
}

1.) Create the path to the file
String sdcardPath = Environment.getExternalStorageDirectory().toString();
String filePath = sdCardPath + "<YOUR_PATH_LIKE_/Downloads>" + "Filename";
2.) Create the file:
File directory = new File(filePath);

Related

How to download Firebase Realtime Database images that are displayed in recyclerview into device storage? [duplicate]

I have a PDF and some doc files kept in firebase storage.
How can I download the file from Firebase Storage to the External storage of my device?
public void writeExternalStorage() {
String filename;
String completepath;
mref = FirebaseStorage.getInstance().getReference();
StorageReference filepath = mref.child("MyFiles").child("firstFile.pdf");
InputStream inputStream = null;
File file = null;
FileOutputStream fileOutputStream = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/TestPurpose");
// Log.d("PATH", file.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want to download the Firstfile.pdf file to the External_storage's Document/TestPurpose/ Folder. How it can be done??
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"/>

How to download multiple files of firebase Storage Android?

I am downloading files from firebase storage
But I can only download one by one
Can I download multiple files at once?
Is it the best way to repeat the same code?
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference islandRef = storageRef.child(filename);
final String saveFilename = filename;
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/down/");
// If no folders
if (!dir.exists()) {
dir.mkdirs();
}
final File localFile = new File(dir,saveFilename);
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
Simply call putFile once for each file you want to download. You will need a different reference and local file for each call.
FileDownloadTask task1 = storageRef1.getFile(localFile1);
FileDownloadTask task2 = storageRef2.getFile(localFile3);
FileDownloadTask task3 = storageRef3.getFile(localFile3);
You can then wait for all them to complete with Tasks.whenAll():
Tasks.whenAll(task1, task2, task3)
.addOnSuccessListener(new OnSuccessListener<List<Task<*>>() {
#Override
public void onSuccess(Task task) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
There is no specific API to download multiple files. You'll just have to download them by calling the same API for each file.

How to create a custom directory in internal storage to save the downloaded file?

Am working with firebase for an app. I have manually uploaded a pdf file into the firebase storage so that the users could download it using the app. The downloaded files gets stored in Android -> data -> FileName -> directory -> file. But I need a custom directory to save the files directly in the internal storage.
public void downloadFile(){
str = FirebaseStorage.getInstance().getReference();
final File mydir = this.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
ref = str.child("AI (presentation).pptx");
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFiles(MainActivity.this,"AI",".ppt",mydir ,url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
public void downloadFiles(Context context, String fileName, String fileExtension, File destinationDirectory, String url) {
DownloadManager downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, "" + destinationDirectory, fileName + fileExtension);
downloadmanager.enqueue(request);
}
You don't need to use DownloadManager.
Instead of that, you can use StorageReferenece.getBytes() and save file manually.
private static final long DOWNLOAD_LIMIT = 1024 * 1024; // you can change this
public void downloadFile(){
StorageReference ref = FirebaseStorage.getInstance().getReference("AI (presentation).pptx");
ref.getBytes(DOWNLOAD_LIMIT).addOnSuccessListener(new OnSuccessListener<byte[]>()
{
#Override
public void onSuccess(byte[] bytes) {
final String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/mydir/AI (presentation).pptx";
try {
writeToFile(bytes, path);
} catch (IOException e) {
e.printStackTrace();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e(TAG, "fail to download: " + exception);
}
});
}
public void writeToFile(byte[] data, String fileName) throws IOException{
FileOutputStream out = new FileOutputStream(fileName);
out.write(data);
out.close();
}

Donwloading files from Firebase to Android

I have stored some doc files in a folder "Colleges_names" in Firebase storage. I want to download them in my android app. When I click the required button to download file nothing happens.
public void onClick(View view) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://du-admissions-app.appspot.com");
StorageReference islandRef = storageRef.child("COLLEGES-NAMES").child("CLG_BA(ENGLISH).docx");
File rootPath = new File(Environment.getExternalStorageDirectory(), "file_name");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,"CLG_BA(ENGLISH).docx");
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());
}
});
You can't retrieve those files with their extension, you should upload your files programmatically first, get the downloadUrl() of the file uploaded and then retrieve that downloadUrl() and being the download of the files.
I would recommend you to read this.

In Android, where does the file downloaded from Firebase storage get stored?

I uploaded a file to Firebase Storage from my project console. Now, I downloaded that file from my app using the method 'Download to a local file' as mentioned in the Firebase Storage documentation, but I am not able to find the downloaded file on my phone.
Can someone tell me where does that file get downloaded to?
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
final StorageReference storageReference = firebaseStorage.getReferenceFromUrl("gs://ldq-app-d2e6b.appspot.com");
button_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = new String(editText_file.getText().toString());
StorageReference childReference = storageReference.child("Quizzes");
StorageReference fileReference = storageReference.child("Quizzes/" + fileName + ".pdf");
File localFile = null;
try {
localFile = File.createTempFile(fileName, "pdf");
}
catch (IOException ioe){
Toast.makeText(getContext(), "File creation failed", Toast.LENGTH_SHORT).show();
}
fileReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getContext(),"File downloaded",LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(),"Download failed. Try again!", LENGTH_SHORT).show();
}
});
//Toast.makeText(getContext(),"Button working",LENGTH_SHORT).show();
}
});
As per Firebase Document, they are creating a temporary file for saving Image from Url. Link
File localFile = File.createTempFile("images", "jpg");
If you want to store it on phone's internal memory or in external memory then just create a File with storage path and pass it to FileDownloadTask.
File storagePath = new File(Environment.getExternalStorageDirectory(), "directory_name");
// Create direcorty if not exists
if(!storagePath.exists()) {
storagePath.mkdirs();
}
final File myFile = new File(storagePath,"file_name");
yourStorageRef.getFile(myFile).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
}
});

Categories

Resources