How to get a list of all files in Cloud Storage in a Firebase app?

后端 未结 19 1015
傲寒
傲寒 2020-11-21 11:25

I\'m working on uploading images, everything works great, but I have 100 pictures and I would like to show all of them in my View, as I get the complete list of

19条回答
  •  天涯浪人
    2020-11-21 11:51

    I faced the same issue, mine is even more complicated.

    Admin will upload audio and pdf files into storage:

    • audios/season1, season2.../class1, class 2/.mp3 files

    • books/.pdf files

    Android app needs to get the list of sub folders and files.

    The solution is catching the upload event on storage and create the same structure on firestore using cloud function.

    Step 1: Create manually 'storage' collection and 'audios/books' doc on firestore

    Step 2: Setup cloud function

    Might take around 15 mins: https://www.youtube.com/watch?v=DYfP-UIKxH0&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=1

    Step 3: Catch upload event using cloud function

    import * as functions from 'firebase-functions';
    import * as admin from 'firebase-admin';
    admin.initializeApp(functions.config().firebase);
    const path = require('path');
    
    export const onFileUpload = functions.storage.object().onFinalize(async (object) => {
            let filePath = object.name; // File path in the bucket.
            const contentType = object.contentType; // File content type.
            const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
            if (metageneration !== "1") return;
    
            // Get the file name.
            const fileName = path.basename(filePath);
            filePath = filePath.substring(0, filePath.length - 1);
            console.log('contentType ' + contentType);
            console.log('fileName ' + fileName);
            console.log('filePath ' + filePath);
            console.log('path.dirname(filePath) ' + path.dirname(filePath));
            filePath = path.dirname(filePath);
            const pathArray = filePath.split("/");
            let ref = '';
            for (const item of pathArray) {
                if (ref.length === 0) {
                    ref = item;
                }
                else {
                    ref = ref.concat('/sub/').concat(item);
                }
            }
    
            ref = 'storage/'.concat(ref).concat('/sub')
            admin.firestore().collection(ref).doc(fileName).create({})
                    .then(result => {console.log('onFileUpload:updated')})
                    .catch(error => {
                        console.log(error);
                    });
        });
    

    Step 4: Retrieve list of folders/files on Android app using firestore

    private static final String STORAGE_DOC = "storage/";
        public static void getMediaCollection(String path, OnCompleteListener onCompleteListener) {
            String[] pathArray = path.split("/");
            String doc = null;
            for (String item : pathArray) {
                if (TextUtils.isEmpty(doc)) doc = STORAGE_DOC.concat(item);
                else doc = doc.concat("/sub/").concat(item);
            }
            doc = doc.concat("/sub");
    
            getFirestore().collection(doc).get().addOnCompleteListener(onCompleteListener);
        }
    

    Step 5: Get download url

    public static void downloadMediaFile(String path, OnCompleteListener onCompleteListener) {
            getStorage().getReference().child(path).getDownloadUrl().addOnCompleteListener(onCompleteListener);
        }
    

    Note

    We have to put "sub" collection to each item since firestore doesn't support to retrieve the list of collection.

    It took me 3 days to find out the solution, hopefully will take you 3 hours at most.

    Cheers.

提交回复
热议问题