How to upload multiple files to Firebase?

前端 未结 8 1878
既然无缘
既然无缘 2020-12-04 16:44

Is there a way to upload multiple files to Firebase storage. It can upload single file within single attempt as follows.

fileButton.addEventListener(\'chang         


        
8条回答
  •  半阙折子戏
    2020-12-04 17:38

    This is a modification of the marked answer for those looking to wait for each upload to complete before the other starts.

    As the marked answer stands, the promise is not resolved or rejected so when the upload begins from the loop everything just starts, the 1st file, 2nd.....

    Think of 3 uploads each 20mb. The loop will call the upload function almost at the same time, making them run almost concurrently.

    This answer solves this using async/await to handle the promises

    fileButton.addEventListener('change', async function(e){ 
        //Get files
        for (var i = 0; i < e.target.files.length; i++) {
            var imageFile = e.target.files[i];
            await uploadImageAsPromise(imageFile).then((res)=>{
             console.log(res);
              });
        }
    });
    
    //Handle waiting to upload each file using promise
    async function uploadImageAsPromise (imageFile) {
        return new Promise(function (resolve, reject) {
            var storageRef = firebase.storage().ref(fullDirectory+"/"+imageFile.name);
            var task = storageRef.put(imageFile);
    
            //Update progress bar
            task.on('state_changed',
                function progress(snapshot){
                    var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 
                         100;
                },
                function error(err){
                    console.log(err);
                    reject(err);
                },
                function complete(){
                    var downloadURL = task.snapshot.downloadURL;
                    resolve(downloadURL);
                }
            );
        });
    }
    

提交回复
热议问题