Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all files from firebase storage?

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 ?

like image 720
P.E Avatar asked Mar 06 '23 22:03

P.E


2 Answers

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 {
like image 81
Rosário Pereira Fernandes Avatar answered Mar 09 '23 10:03

Rosário Pereira Fernandes


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());
        }
    });
}
like image 30
Gastón Saillén Avatar answered Mar 09 '23 11:03

Gastón Saillén