feat: added progress bar for file upload

This commit is contained in:
lacni
2025-02-26 23:31:31 -05:00
parent eb91d8b298
commit db60f355b2

View File

@@ -118,6 +118,7 @@ fileInput.addEventListener("change", (e) => {
const row = document.createElement("tr");
row.innerHTML = `
<td>${file.name}</td>
<td><progress max="100"></progress></td>
<td>${(file.size / 1024).toFixed(2)} kB</td>
<td><a onclick="deleteRow(this)">Remove</a></td>
`;
@@ -153,6 +154,10 @@ fileInput.addEventListener("change", (e) => {
// Append the row to the file-list table
fileList.appendChild(row);
//Imbed row into the file to reference later
file.htmlRow = row;
// Append the file to the hidden input
fileNames.push(file.name);
}
@@ -208,12 +213,13 @@ const uploadFiles = (files) => {
formData.append("file", file, file.name);
}
fetch(`${webroot}/upload`, {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then((data) => {
let xhr = new XMLHttpRequest();
xhr.open("POST", `${webroot}/upload`, true);
xhr.onload = (e) => {
let data = JSON.parse(xhr.responseText);
pendingFiles -= 1;
if (pendingFiles === 0) {
if (formatSelected) {
@@ -221,9 +227,28 @@ const uploadFiles = (files) => {
}
convertButton.textContent = "Convert";
}
//Remove the progress bar when upload is done
for (const file of files) {
let progressbar = file.htmlRow.getElementsByTagName("progress");
progressbar[0].parentElement.remove();
}
console.log(data);
})
.catch((err) => console.log(err));
};
xhr.upload.onprogress = (e) => {
//All files upload together are binded by the same progress. The loop should probably be on the call to this function to track each upload individually.
let sent = e.loaded;
let total = e.total;
console.log("upload progress:", (100 * sent) / total);
for (const file of files) {
let progressbar = file.htmlRow.getElementsByTagName("progress");
progressbar[0].value = ((100 * sent) / total);
}
};
xhr.send(formData);
};
const formConvert = document.querySelector(`form[action='${webroot}/convert']`);