html
<input type="file" id="file"/>
<span id="progress_files"></span>
js
let progress_counter = 0;
let last_fi = null;
document.getElementById('file').onchange = upload_file;
function upload_file() {
let fi = document.getElementById('file').files[0];
const my_form = new FormData();
my_form.append("file", fi);
let file_id = null;
if (fi !== undefined) {
if (last_fi !== fi) {
let file_id = 'progress_file_' + progress_counter;
create_file_progress(file_id, fi.name);
const xhr = new XMLHttpRequest();
post_file(xhr, file_id).send(my_form);
last_fi = fi;
fi = undefined;
file_id = null;
}
}
}
function post_file(xhr, file_id) {
xhr.open("POST", "/upload");
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
const complete = (event.loaded / event.total * 100 | 0);
document.getElementById(file_id + '_percent').innerText = complete + ' %';
}
});
return xhr;
}
function create_file_progress(file_id, file_name) {
if (document.getElementById(file_id) === undefined || document.getElementById(file_id) === null) {
const progress_title = '<p>' + file_name + '</p>' + '<p id="' + file_id + '_percent"> 0 %</p>';
document.getElementById('progress_files').innerHTML += progress_title;
progress_counter += 1;
}
}