DEV Community

loading...

Discussion on: 10 useful HTML file upload tips for web developers

Collapse
p810 profile image
Payton Bice • Edited

Something to note about the progress bar example is that it may not finish for users who have fast connections. I was testing it out and noticed that a progress event was fired around the 1% mark for a couple of files, but wasn't fired again before readyState indicated that the file upload was done. For a production implementation, you'll probably also want to hook into the loadend event to account for this. Here's a slightly modified version of the above example that demonstrates this:

fileUploader.addEventListener('change', (event) => {
  const files = event.target.files;
  const file = files[0];
  reader.readAsDataURL(file);

  reader.addEventListener('progress', updateProgressBar);
  reader.addEventListener('loadend', updateProgressBar);

  function updateProgressBar(event) {
    if (! event.loaded || ! event.total) {
      return;
    }

    const percent = (event.loaded / event.total) * 100;
    progress.value = percent;
    document.getElementById('progress-label').innerHTML = Math.round(percent) + '%';

    if (percent === 100) {
      let msg = `<span style="color:green;">File <u><b>${file.name}</b></u> has been uploaded successfully.</span>`;
      feedback.innerHTML = msg;
    }
  }
});
Enter fullscreen mode Exit fullscreen mode
Collapse
atapas profile image
Tapas Adhikary Author

Great point Payton! I am gonna look into that and modify. Thanks for reading and commenting.