I've searched for hours and tried more things than I can count on both hands. But, this is perplexing me.
I'm trying to show upload progress when uploading a file. I'm using the jQuery ajax method to do this while adding in an event listener for the progress. The upload works fine and gets uploaded without any issue. However, the progress is always at 100 right from the start. The only exception to this is if I hit the upload button repeatedly in quick succession in which case it seems to show progress. Sometimes this progress will be 50% then 100% within a second on a 25mb file, so not confident this is real progress. Other times it does actually look like it's showing real progress.
I've also tried a pure JavaScript approach and the results are exactly the same.
Any assistance in helping identify why this is happening would be greatly appreciated.
upload_handler.js
$('#upload_form').submit(function(event){
event.preventDefault();
var form = $('#upload_form')[0];
var fd = new FormData(form);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
var percent = (evt.loaded / evt.total) * 100;
console.log(percent);
}, false);
return xhr;
},
url: "https://example.com/upload_file.php",
method: "POST",
data: fd,
contentType: false,
processData: false,
})
.done(function(){
console.log('Done');
})
.fail(function(){
console.log('Fail');
})
.always(function(){
console.log('Always');
});
})
Console Output
When the form is submitted the console will read:
100 - this shows immediately when the form is submitted
Done - this shows a couple seconds after submitting the form
Always - shows immediately after Done
upload_file.php
<?php
$file = $_FILES['file_upload'];
$file_dir = __DIR__ . '/test_uploads/';
if( is_dir( $file_dir ) === false ) {
mkdir(
$file_dir,
0755
);
}
$file_path = "{$file_dir}{$file['name']}";
if( move_uploaded_file( $file['tmp_name'], $file_path ) ) {
error_log("File uploaded to {$file_path}");
echo 'success';
} else {
error_log("Failed to upload file to {$file_path}");
echo 'failed';
}
EDIT