Handling File Uploads and Displaying Progress

upload

To create a file upload input with progress using HTML and JavaScript without a server, you can utilize the FileReader API and progress events. Here’s an example implementation:

  1. Create an HTML form with an input element of type file and a progress bar:
<form>
<input type="file" id="file-input" />
<progress id="upload-progress" value="0" max="100"></progress></form>  
  • Add JavaScript code to handle the file upload and update the progress bar:
Add JavaScript code to handle the file upload and update the progress bar:
const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('upload-progress');

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

  reader.onprogress = (event) => {
    if (event.lengthComputable) {
      const progress = (event.loaded / event.total) * 100;
      progressBar.value = progress;
    }
  };

  reader.onload = (event) => {
    // File loaded successfully
    const fileData = event.target.result;
    console.log('File uploaded successfully!', fileData);
  };

  reader.readAsDataURL(file);
});
  • When the user selects a file using the file input, the change event listener is triggered. The FileReader API is used to read the file data as a data URL asynchronously. The onprogress event updates the progress bar based on the loaded percentage.
  • Once the file is loaded successfully, the onload event listener is triggered. You can access the file data using event.target.result. In this example, the file data is displayed as a log message.

Here’s an updated implementation of the HTML form with an input element of type file and a progress bar that displays the upload progress percentage:

<form>
  <input type="file" id="file-input" />
  <progress id="upload-progress" value="0" max="100"></progress>
  <span id="progress-percentage">0%</span>
</form>

In this version, we have added a span element with the id progress-percentage to display the upload progress as a percentage.

To update the progress bar with the percentage information, you can modify the JavaScript code as follows:

const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('upload-progress');
const progressPercentage = document.getElementById('progress-percentage');

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

  reader.onprogress = (event) => {
    if (event.lengthComputable) {
      const progress = (event.loaded / event.total) * 100;
      progressBar.value = progress;
      progressPercentage.textContent = `${progress.toFixed(2)}%`;
    }
  };

  reader.onload = (event) => {
    // File loaded successfully
    const fileData = event.target.result;
    console.log('File uploaded successfully!', fileData);
  };

  reader.readAsDataURL(file);
});

Now, the progressPercentage.textContent is updated with the progress value as a percentage, rounded to two decimal places. The template literal ${progress.toFixed(2)}% generates the string representation of the progress value followed by a percentage symbol.

Check this on codepen

Remember, this implementation only handles the client-side processing of the file. To upload the file to a server, further modifications and server-side integration would be required. If you need to upload the file to a server, you would need to modify the code and make an appropriate AJAX or fetch request to the server endpoint of your choice.

To upload the file to a server using AJAX, you can modify the JavaScript code to make an asynchronous XMLHttpRequest (XHR) POST request to the server’s updated implementation:

const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('upload-progress');
const progressPercentage = document.getElementById('progress-percentage');

fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  const xhr = new XMLHttpRequest();
  
  xhr.open('POST', '/upload', true);
  
  xhr.upload.onprogress = (event) => {
    if (event.lengthComputable) {
      const progress = (event.loaded / event.total) * 100;
      progressBar.value = progress;
      progressPercentage.textContent = `${progress.toFixed(2)}%`;
    }
  };
  
  xhr.onload = (event) => {
    if (xhr.status === 200) {
      // File uploaded successfully
      const response = JSON.parse(xhr.responseText);
      console.log('File uploaded successfully!', response);
    } else {
      console.error('Error uploading file.');
    }
  };
  
  const formData = new FormData();
  formData.append('file', file);
  
  xhr.send(formData);
});

In this updated code, I use the XMLHttpRequest object (xhr) to make a POST request to the /upload endpoint on the server. We set the request method to 'POST' and the third parameter of xhr.open() to true to make an asynchronous request.

The xhr.upload.onprogress event handler is used to update the progress bar and the percentage as the file is being uploaded.

The xhr.onload event handler is triggered when the upload is completed. If the server responds with a status code of 200 (indicating a successful upload), I can access the response using xhr.responseText. In this example, the response is parsed as JSON and logged to the console.

To send the file to the server, we create a new FormData object (formData) and append the file to it using formData.append('file', file). We then pass the formData object as the argument to xhr.send().

Please note that in this example, the server endpoint /upload is used as a placeholder. You would need to replace it with the actual URL of your server’s upload endpoint.

Remember to handle server-side processing and file storage on your server to complete the file upload process.