Reputation: 96
I have a problem with the upload of a form using javascript and monitoring it's progress.
The problem is that the XMLHttpRequest progress event is raised with a strange behavior. It reaches too fast 100% when the real upload is not finished, sometimes it's just started, monitored with chrome dev tools and system monitor.
So while the calculated progress is 100% i have too wait long time for send the file with the page apparently stucked. I've read that antivirus can be the reason of that but this is not the case. I don't have antivirus and I turned off firewall too. I tried with both chrome, firefox in windows and ubuntu and libraries such as jquery form plugin with the same behavior.
Someone has an explanation of this strange behavior. What is the XMLHttpRequest progress event loaded attribute actually counting?
Thank you in advance. I fell like banging on the wall for a day.
Here a small piece of code for reproduce the issue:
<?php
echo "Hello!";
if(isset($_FILES['file'])){
echo " File received";
return;
}
?>
<form method='post' action='' enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit'>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form').submit(function(e){
e.preventDefault();
ajax = new XMLHttpRequest();
ajax.onreadystatechange = function ()
{
console.log("READY STATE CHANGED");
console.log(ajax);
};
ajax.upload.addEventListener("progress", function (event) {
var percent = (event.loaded / event.total) * 100;
console.log(percent);
});
ajax.open("POST", $(this).attr('action'), true);
ajax.send(new FormData(this));
return false;
});
});
</script>
Upvotes: 4
Views: 2443
Reputation: 1
XMLHttpRequestUpload
progress
event is dispatched roughly every 50ms. XMLHttpRequestUpload
dispatches event as to body
transmitted bytes. As far as aware, XMLHttpRequestUpload
does not monitor network performance in relation to the transmitted bytes of body
, and does not await a response from server.
See Make upload progress notifications
When it is said to make progress notifications, while the download is progressing, queue a task to fire a progress event named progress about every 50ms or for every byte received, whichever is least frequent.
When it is said to make upload progress notifications run these steps:
While the request entity body is being uploaded and the upload
complete flag is false, queue a task to fire a progress event named
progress
at the XMLHttpRequestUpload
object about every 50ms or for
every byte transmitted, whichever is least frequent.
If the request entity body has been successfully uploaded and the upload complete flag is still false, queue a task to run these substeps:
Set the upload complete flag to true.
Fire a progress event named load
at the XMLHttpRequestUpload
object.
Fire a progress event named loadend
at the XMLHttpRequestUpload
object.
Upvotes: 2