Last updated on November 24th, 2018 at 08:54 pm

Axios is one the most useful Promise based HTTP library used with ReactJS and AngularJs to make a call to the server. Axios is supported by most of the browser. Now in this post, I will explain to you how we can upload image or file to the server with the progress bar. Axios is also very best alternate of Ajax Call and also very fast and lightweight. You can easily add this in your project using CDN or bower. Axios come with no of operations which help you to make a single request or multiple requests in same time. 

Demo Link

Axios come with no of features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

If you know how Ajax then it is very easy to understand Axios Call, please check below sample code. But before we start we need to add CDN link to load this Plugin in our project.

Installing Axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Get Request using Axios

axios.get('My_API_URL')
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

Post Request using Axios

axios.post('My_API_URL', {name: 'Aneh'})
.then(function (response) {
    console.log(response);
  })
.catch(function (error) {
    console.log(error);
});

Or you can make call in this way

axios({
  method:'post',
  url:'MY_API_URL',
  data:$("#formID").serialize() // Or you can use {name: 'Aneh'}
})
.then(function(response) {
  console.log(response);
});

Axios supported all request methods:- GET, POST, PUT, DELETE.

Upload image with progress bar

Most time we need to upload a file to the server and we always want to show the progress bar for doing this there are no of the library but I like Axios it is very easy to use and no need to config other things. Check below code and see how we can upload image and show progress bar

var data = new FormData();
data.append('file', input.files[0]);
var config = {
    onUploadProgress: function(progressEvent) {
    var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
       console.log("Progress:-"+percentCompleted);
    }
};
axios.post('MY_API_URL', data, config)
.then(function (res) {
})
.catch(function (err) {
    console.log(err.message);
});

If you want to learn more about Axios you can check this official library

If this post helps you then like our page.