Browse Source

feat: added progress bar for file upload

lacni 5 months ago
parent
commit
db60f355b2
1 changed files with 40 additions and 15 deletions
  1. 40 15
      public/script.js

+ 40 - 15
public/script.js

@@ -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,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']`);