How to get all files from firebase storage? - android

I have uploaded some files into Firebase directory and I want to list them and download one by one.There is no API/Documentation fo this.Could you help me ?

As of July 2019, version 18.1.0 of the Cloud Storage SDK now supports listing all objects from a bucket. You simply need to call listAll() in a StorageReference:
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
// Now we get the references of these images
storageRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult result) {
for(StorageReference fileRef : result.getItems()) {
// TODO: Download the file using its reference (fileRef)
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
// Handle any errors
}
});
If you want to download these files, you can use one of the options shown in the Docs.
Please note that in order to use this method, you must opt-in to version 2 of Security Rules, which can be done by making rules_version = '2'; the first line of your security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {

first , you should get the file download Url to retrieve it, the easiest way is to upload a file and generate the download Url in your database, so after that you just go and retrieve each file from the storage like this :
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());
}
});
}

I personally use this method, whenever you upload a file, save its download URL in your Firebase Database, if you are uploading multiple files then save it in an array. There is no method for Firebase Storage android to download and upload multiple files in one go.
Whenever you want to download files access your firebase database for those URL's.

Related

Downloaded files from firebase storage aren't readable

i succesfully download files from firebase storage and save it but the downloaded file which is pdf type isn't openable
here is the method
#Override
public void download(Book book) {
FirebaseStorage storage = FirebaseStorage.getInstance();
File root = new File(Environment.getExternalStorageDirectory(),"Books");
if(!root.exists()){
root.mkdir();
}
storage.getReference().child(book.getmTitle()+".pdf").getFile(new File(root,book.getmTitle())).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(),"Downloaded successfully",Toast.LENGTH_LONG).show();
}
});
}
i am sure that the book.getmTitle() returns the reference name without the extension 'pdf'
Stupid mistake, all what i had to do is to add the extension to the file name

How to choose specified File to upload to Firebase Storage?

I would like to upload my SQLite database File to Firebase Storage. My problem is that I can only find tutorials where the user has to choose the file manually, but I would like to send a fixed file, so you can't send other data to Firebase storage.
How can I do that?
Thank you.
First get the reference to the firebase storage
// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
Then to upload the file do the following:
Uri file = Uri.fromFile("sqlite_file");
StorageReference filesRef = storageRef.child("files");
uploadTask = filesRef.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
});

Firebase Storage error: error getting token

I am building an android app which allows users to upload pictures to firebase storage. I am still in development mode so I set up my storage rules to public. When the user selects a picture to upload, the file is not uploaded but the download URL is returned. Logcat shows the following error
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
And here is my storage rules
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my android java code:
private void uploadPic() {
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
Uri fileUrl = Uri.fromFile(new File(filePath));
String fileExt = MimeTypeMap.getFileExtensionFromUrl(fileUrl.toString());
final String fileName = UUID.randomUUID().toString()+"."+fileExt;
StorageReference profilePicsRef = mStorageRef.child("profile_pics/"+fileName);
profilePicsRef.putFile(fileUrl)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.d("DOWNLOAD_URL", downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(getApplicationContext(), "Error: "+exception.toString(), Toast.LENGTH_LONG).show();
}
});
}
Any help will be greatly appreciated.
UPDATE
I have narrowed down the problem: I have two folders in storage, I can upload to the "Videos" folder, but not to the "profile_pics" folder or any other folder. Why is this happening?
For some reason unknown to mere mortals, the gods have refused upload to any folder that starts with "profile". I had to create another folder "users_profile_pic". Three days wasted!

Uploading and downloading files to/from Google Cloud Firestore

I see that the Firebase has already a new beta version released, called Cloud Firestore. In the documentation all operations with the documents are described very well, but I am not able to find anything about uploading and downloading media files into the Cloud Firestore using Android...
Does anyone has any information/tutorial etc for uploading/downloading media files (for example mp3 files and images)?
Thank you very much in advance for the answers!
You can't store files to Firebase Cloud Firestore instead you can use the combination of Firebase Storage and Firebase Cloud Firestore to active the desired functionality.
Firebase Storage is to storage files and download from it.
Firebase Realtime Database is to store json no-sql database on it.
Firebase Cloud Firestore is advanced version of Firebase realtime database the difference from Realtime database is that it is Document based non-sql database.
Suppose you need to develop an application with database and storage you need combination of any of Database with Firebase Storage. Store files in firebase storage and save their urls in firebase realtime or firebase cloud firestore for downloading and uploading them.
To Upload file on firebase storage :
FirebaseStorage firebaseStorage;
//for firebase storage
firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReference;
storageReference = firebaseStorage.getReferenceFromUrl("url");
final StorageReference imageFolder = storageReference.child("" + imageName);
imageFolder.putFile(saveUri).addOnSuccessListener(new OnSuccessListener < UploadTask . TaskSnapshot >() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//submitted sucessfully
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener < Uri >() {
#Override
public void onSuccess(Uri uri) {
Log.wtf(TAG, "download image path : " + uri.toString());
//now you have path to the uploaded file save this path to your database
uploadDataToUserUploadedImage(uri);
}
}).addOnFailureListener(new OnFailureListener () {
#Override
public void onFailure(#NonNull Exception e) {
getMvpView().stopProgressLoading();
getMvpView().onError("Fail to submit feedback " + e.getMessage());
getMvpView().hideLoading();
return;
}
});
}
}).addOnProgressListener(new OnProgressListener < UploadTask . TaskSnapshot >() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress =(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
getMvpView().publishProgress((int) progress);
Log.d(TAG, "onProgress: " + progress);
}
}).addOnFailureListener(new OnFailureListener () {
#Override
public void onFailure(#NonNull Exception e) {
getMvpView().hideLoading();
getMvpView().stopProgressLoading();
getMvpView().onError("Error: " + e.getMessage());
}
});

Android - Download File from Firebase by means of only URL

I'm developing a simple Android application that downloads a file from Firebase storage.
Is there any way to download a file getting only a link to the file? I found a few methods but they were requiring also the name of file
I don't know the name of downloading file, I need to download the file knowing only its URL.
Just try this :
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl("YOUR_FIREBASE_STORAGE_URL");
File localFile = File.createTempFile("PREFIX_FILE", "SUFFIX_FILE");
httpsReference.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
}
});
Firebase Storage documentation.

Categories

Resources