How to upload multiple files to Firebase?

前端 未结 8 1883
既然无缘
既然无缘 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

    @isuru, the guy who uploaded the question has a great solution provided below. But, some of the firebase functions have been updated. So, I have just updated the solution with the new updates in the Firebase.

      //Firebase Storage Reference
      const storageRef = firebase.storage().ref();
    
      //Upload Image Function returns a promise  
      async function uploadImageAsPromise(imageFile) {
        return new Promise(function (resolve, reject) {
          const task = storageRef.child(imageFile.name).put(imageFile);
    
          task.on(
            "state_changed",
            function progress(snapshot) {
              const percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            },
    
            function error(err) {
              reject(err);
            },
    
            async function complete() {
              //The getDownloadURL returns a promise and it is resolved to get the image url.
              const imageURL = await task.snapshot.ref.getDownloadURL();
              resolve(imageURL);
            }
          );
        });
      }
      
      //Handling the files
      fileButton.addEventListener('change', function(e){ 
        const promises = [];
        for(const file of e.target.files){//Instead of e.target.files, you could also have your files variable
            promises.push(uploadImageAsPromise(file))
        }
        
        //The Promise.all() will stop the execution, until all of the promises are resolved.
        Promise.all(promises).then((fileURLS)=>{
            //Once all the promises are resolved, you will get the urls in a array.
            console.log(fileURLS)
        })
      });
    

提交回复
热议问题