Usually, while uploading a file, we want to show the progress of the upload. We can get the progress information from the upload event of the XMLHttpRequest object. The upload event is triggered when the upload process starts. The progress event is triggered when the upload process is in progress. The load event is triggered when the upload process is completed.

In axios, we can get the progress information from the onUploadProgress event. The onUploadProgress event is triggered when the upload process is in progress. The event object contains the following properties:

  • lengthComputable: A Boolean that indicates whether or not the total number of bytes is known.
  • loaded: The number of bytes of the file that have been uploaded.
  • total: The total number of bytes in the file.

The following code shows how to get the progress information from the onUploadProgress event.

const onUploadProgress = (progressEvent) => {
  const { loaded, total } = progressEvent;
  let percent = Math.floor((loaded * 100) / total);
  if (percent < 100) {
    console.log(`${loaded} bytes of ${total} bytes. ${percent}%`);
  }
};

  

The following code shows how to use the onUploadProgress event.

const uploadFile = (file) => {
  const url = "https://example.com/upload";
  const formData = new FormData();
  formData.append("file", file);
  return axios.post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress,
  });
};

The following code shows how to use the uploadFile function.

const file = document.getElementById("file").files[0];
uploadFile(file).then((response) => {
  console.log(response.data);
});

The following code shows how to use the uploadFile function with async/await.

const file = document.getElementById("file").files[0];
const response = await uploadFile(file);
console.log(response.data);

The following code shows how to use the uploadFile function with Promise.

const file = document.getElementById("file").files[0];
uploadFile(file)
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

The following code shows how to use the uploadFile function with Promise.all.

const file1 = document.getElementById("file1").files[0];
const file2 = document.getElementById("file2").files[0];
const file3 = document.getElementById("file3").files[0];
Promise.all([uploadFile(file1), uploadFile(file2), uploadFile(file3)])
  .then((responses) => {
    console.log(responses);
  })
  .catch((error) => {
    console.log(error);
  });

Example Implementation

Here is complete example implementation of upload progress with axios.

<!doctype html>
<html>
  <head>
    <title>axios - file upload example</title>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>
  </head>
  <body class="container">
    <h1>file upload</h1>

    <form role="form" class="form" onsubmit="return false;">
      <div class="form-group">
        <label for="file">File</label>
        <input id="file" type="file" class="form-control"/>
      </div>
      <button id="upload" type="button" class="btn btn-primary">Upload</button>
    </form>

    <div id="output" class="container"></div>

    <script src="/axios.min.js"></script>
    <script>
      (function () {
        var output = document.getElementById('output');
        document.getElementById('upload').onclick = function () {
          var data = new FormData();
          data.append('foo', 'bar');
          data.append('file', document.getElementById('file').files[0]);

          var config = {
            onUploadProgress: function(progressEvent) {
              var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
            }
          };

          axios.put('/upload/server', data, config)
            .then(function (res) {
              output.className = 'container';
              output.innerHTML = res.data;
            })
            .catch(function (err) {
              output.className = 'container text-danger';
              output.innerHTML = err.message;
            });
        };
      })();
    </script>
  </body>
</html>

Server response time and upload progress

In some case server may process files after upload. Processing can be anything from uploading it to a cloud storage to converting it to a different format. In this case, server response time can be very long.

onUploadProgress event will be triggered only when file is uploaded to server. It will not be triggered when server is processing file.