Easy to upload a image with a progress bar by axios javascript library?

(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 );
              document.getElementById('output').innerHTML = percentCompleted;
            }
          };
          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;
            });
        };
      })();

We require the input file type for uploading the file, place an id on field. That we will use later in javaScript.

<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>

Javascript powerful scripting language to manipulate with the UI. Let’s start with to attach the on-click delegate with the upload input id, by creation get new FormData(); object you have to pass the file data into the post request.

Before calling the axios you need to bind the onUploadProgress with custom data by creating the config var init it with config object onUploadProgress do inside the progress work.

At last you need to call the axios post request by pass the three parameters.

  1. URL
  2. FormData Object
  3. Config data.
Scroll to Top