jeudi 5 mars 2020

Web apps only upload the first item to firebase

A fresh learner on web development and wanted to build a simple web apps that can upload multiple images to firebase storage. I was able to get everything worked except for the uploading part.

Was wondering if anyone could point out the mistakes that I had made. Thanks.

fileButton.addEventListener('change',(e) => {

   totalFile = e.target.files.length;

   console.log(e.target.files.length);
   for (var i = 0; i < e.target.files.length; i++) {
       var imageFile = e.target.files[i];
   }

   uploadButton.addEventListener('click',(e)=> {
       if(totalFile < 1) {
           window.alert("No file chosen yet.")

           $("#uploader")
            .css("width",0+ "%")
            .attr("aria-valuenow",0)
            .text("Please choose a file to upload.");

       }
       else
       {
           uploadImageAsPromise(imageFile);
       }
   });

});

And here's the handling part

//Handle waiting to upload each file using promise
function uploadImageAsPromise (imageFile) {
return new Promise(function (resolve, reject) {

    //storage reference
    var storageRef = firebase.storage().ref('images/'+imageFile.name);

    //Upload file
    var task = storageRef.put(imageFile);
    var current_progress = 0;

    //Update progress bar
    task.on('state_changed',


        function progress(snapshot){


            //Calculate the progress
            current_progress =(snapshot.bytesTransferred / snapshot.totalBytes) * 100;

            //Display the progress
            $("#uploader")
            .css("width",Math.round(current_progress) + "%")
            .attr("aria-valuenow",current_progress)
            .text(Math.round(current_progress) + "% completed");


        },
        function error(err){
            window.alert("Your files are not uploaded.");
        },
        function complete(snapshot){

            var downloadURL = task.snapshot.downloadURL;


            //Display and dismiss alert after 5 seconds
            if(current_progress == 100){
                handleAlert(1);  // code 1: success

            }  
        }
    );
});

}




Aucun commentaire:

Enregistrer un commentaire