Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest onprogress not firing on async = false

When sending a XMLHttpRequest with async = false, the xhr.upload.onprogress events is never fired doing file upload.

Source:

var form = new FormData();
form.append("name", files[i].name);
form.append("size", files[i].size);
form.append("type", files[i].type);
form.append("image", files[i]);

var xhr = new XMLHttpRequest();

xhr.upload.onprogress = function(evt){
    alert("Progress event fired!");
    if (evt.lengthComputable) 
    {
        var percentComplete = (evt.loaded / evt.total)*100; 
        console.log(percentComplete); 
    } 
};

xhr.onload = function() {
    console.log(files[i].name + " uploaded!");
};

xhr.open("post", "/images/upload", false);
xhr.send(form);

I have tested this in both Firefox and Chrome.

I have no idea if i missed some documentation but could not find anything that indicated that the xhr.upload.onprogress event is not fired when async = false?.

If i change the request to run with async = true it´s fired.

like image 210
tlorentzen Avatar asked Dec 19 '25 20:12

tlorentzen


1 Answers

Basically you should not use synchronous request, especially in file uploads, that may take some time.

Using sync requests, you block thread execution until everything is done (the file is uploaded), and even if the onprogress event would've been fired, you could not update any progress bars because the UI and all other processing (but the file upload) would be blocked.

Those events were created so that you could handle asynchronous requests.

If you read here, you'll see that synchronous requests have been deprecated in some browser versions.

like image 177
Vicentiu Bacioiu Avatar answered Dec 21 '25 10:12

Vicentiu Bacioiu