JavaScript: how to upload a file with axios

JavaScript: how to upload a file with axios

The axios JavaScript library is a powerful and versatile tool that allows to make HTTP requests to a server. Among its main features, it is possible to upload a file to a server.

The axios JavaScript library is a powerful and versatile tool that allows to make HTTP requests to a server. Among its main features, it is possible to upload a file to a server.

To upload a file, you need to create a FormData object and insert the file to be sent inside. Afterwards, it can be used the axios post() method to send the request to the server.


'use strict';

const file = document.getElementById('file').files[0];

const formData = new FormData();
formData.append('file', file);

axios.post('/upload', formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
}).then(response => {
  console.log(response);
}).catch(error => {
  console.log(error);
});

In this example, a FormData object is created and the file to be sent is inserted inside, using the append() method. Next, the axios post() method is used to post the request to the server. It is important to specify the type of content multipart/form-data in the parameters of the request, using the corresponding header.

In conclusion, using the axios library in JavaScript it is possible to easily upload a file to a server.