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"); const row = document.createElement("tr");
row.innerHTML = ` row.innerHTML = `
<td>${file.name}</td> <td>${file.name}</td>
<td><progress max="100"></progress></td>
<td>${(file.size / 1024).toFixed(2)} kB</td> <td>${(file.size / 1024).toFixed(2)} kB</td>
<td><a onclick="deleteRow(this)">Remove</a></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 // Append the row to the file-list table
fileList.appendChild(row); fileList.appendChild(row);
//Imbed row into the file to reference later
file.htmlRow = row;
// Append the file to the hidden input // Append the file to the hidden input
fileNames.push(file.name); fileNames.push(file.name);
} }
@@ -208,22 +213,42 @@ const uploadFiles = (files) => {
formData.append("file", file, file.name); formData.append("file", file, file.name);
} }
fetch(`${webroot}/upload`, { let xhr = new XMLHttpRequest();
method: "POST",
body: formData, xhr.open("POST", `${webroot}/upload`, true);
})
.then((res) => res.json()) xhr.onload = (e) => {
.then((data) => { let data = JSON.parse(xhr.responseText);
pendingFiles -= 1;
if (pendingFiles === 0) { pendingFiles -= 1;
if (formatSelected) { if (pendingFiles === 0) {
convertButton.disabled = false; if (formatSelected) {
} convertButton.disabled = false;
convertButton.textContent = "Convert";
} }
console.log(data); convertButton.textContent = "Convert";
}) }
.catch((err) => console.log(err));
//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);
};
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']`); const formConvert = document.querySelector(`form[action='${webroot}/convert']`);