diff --git a/public/script.js b/public/script.js index 601be47..1e9704a 100644 --- a/public/script.js +++ b/public/script.js @@ -118,6 +118,7 @@ fileInput.addEventListener("change", (e) => { const row = document.createElement("tr"); row.innerHTML = ` ${file.name} + ${(file.size / 1024).toFixed(2)} kB Remove `; @@ -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,22 +213,42 @@ const uploadFiles = (files) => { formData.append("file", file, file.name); } - fetch(`${webroot}/upload`, { - method: "POST", - body: formData, - }) - .then((res) => res.json()) - .then((data) => { - pendingFiles -= 1; - if (pendingFiles === 0) { - if (formatSelected) { - convertButton.disabled = false; - } - convertButton.textContent = "Convert"; + 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) { + convertButton.disabled = false; } - console.log(data); - }) - .catch((err) => console.log(err)); + 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); + }; + + 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']`);