Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xmlhttprequest does not work properly in function

is anyone know why upload.onprogress does not work correctly if it's on separate function?

Code work properly (the progress bar slowly moving):

        xhr.upload.onprogress = function(e) {
            if (e.lengthComputable) {
                progress.value = (e.loaded / e.total) * 100;
            }
        };  

but if I put it into function, it does not work anymore:

xhr.upload.onprogress = uploadProgress(event);

function uploadProgress(e) {
    if (e.lengthComputable) {
        progress.value = (e.loaded / e.total) * 100;
    }
}   

On the second code, the progress bar directly jump into 100% after file finished uploaded instead of, move nicely into 100% during the upload


so, I've tried the solution provided, it actually work, if I put the function inside. Is there no way to put it outside the function?

        function uploadFile(blobFile, fileName) {
            ...
            ...

            // Listen to the upload progress for each upload.
            xhr.upload.onprogress = uploadProgress;

            // Progress Bar Calculation why it has to be in uploadFile function..
            function uploadProgress(e) {
                if (e.lengthComputable) {
                    progress.value = (e.loaded / e.total) * 100;
                }
            }                            

            uploaders.push(xhr);
            xhr.send(fd);
        }  

        //it does not work if I put it outside the function. is there anyway to do this?  
        function uploadProgress(e) {
             if (e.lengthComputable) {
                 progress.value = (e.loaded / e.total) * 100;
             }
        }   
like image 566
Harts Avatar asked Feb 21 '23 03:02

Harts


1 Answers

With uploadProgress(event); you call the function itself and assign the return value to xhr.upload.onprogress instead of assigning it as a callback function:

xhr.upload.onprogress = uploadProgress;
like image 100
ComFreek Avatar answered Feb 24 '23 15:02

ComFreek