How to upload multiple files to Firebase?

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

    We can Combine multiple Promises like this

    Promise.all([promise1, promise2, promise3]).then(function(values) {
      console.log(values);
    });
    

    And we can Chain Promise like this

    return myFirstPromise.then( (returnFromFirst) => {
        //Do something
        return secondPromise();
    }).then( (returnFromSecond) => {
        //Do something
        return thirdPromise();
    }).then( (returnFromThird) => {
        //All Done
    }).catch( (e) =>{}
        console.error("SOMETHING WENT WRONG!!!");
    );
    

    Idea is to combine upload file promises with Promise.all & chain them together to get download URLS after each upload

          Promise.all(
                //Array.map creates a new array with the results 
              // of calling a function for every array element. 
              //In this case Array of "Promises"
                this.state.filesToUpload.map(item => 
                 this.uploadFileAsPromise(item))
              )
                .then(url => {
                  console.log(`All success`);
    
                  //Handle Success all image upload
    
                })
                .catch(error => {
                  console.log(`Some failed: `, error.message);
    
                  //Handle Failure some/all image upload failed             
                });
    
    
      //return a promise which upload file & get download URL 
      uploadFileAsPromise(imageFile) {
            // the return value will be a Promise
            return storageRef
              .child("images/users/" + imageFile.name)
              .put(imageFile.file) 
              .then(snapshot => {
                console.log("Uploaded File:", imageFile.name);
                return snapshot.ref.getDownloadURL().then(downloadURL => {
                  //promise inside promise to get donloadable URL
                  console.log("File available at", downloadURL);
                  );
                });
              })
              .catch(error => {
                console.log("Upload failed:", imageFile.name, error.message);
              });
          }
    

提交回复
热议问题