How to post a file from a form with Axios?

In this article, we are going to discuss making POST requests with form data using the Axios library. Axios is a Promise based HTTP client that can be used for the web as well as for Node.JS development. However, in this article, we are going to strictly refer to client-side use of Axios.

To start off, we need to add axios to our development by using a CDN link :

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"> </script>

In order to use extract data from our form, we are going to use the FormData() method. The formdata method converts the data input in the form in the form of key-value pairs to create a multipart/form-data object.

HTML:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
        content="width=device-width, 
                 initial-scale=1.0">
  <script src=
          crossorigin="anonymous">
  </script>
  <title>Document</title>
</head>
  <body>
  <h3 style="color:green; font-size:25px;">
    Geeks For Geeks
  </h3>
  <form>
    <input name="first-name"/><br>
    <input name="last-name"/><br>
    <input name="address"/><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>

chevron_right


Output:



Axios Post Request Syntax
There are two ways to make an axios post request :

  1. Standard post request:

    axios.post(url, data).then(callbackFn()).catch(callbackFn(err))
    url : The request url for HTTP POST.
    data : An object containing the POST data
    callbackFn() : Callback functions to handle the promise.

  2. Post Request with a configuration object


  3. axios({
    method : ‘post’,
    url : url,
    data : data
    headers : headers
    }).then(callbackFn()).catch(callbackFn())

    method : specifies the HTTP method
    data : an object containing the POST data.
    headers(optional) : An object to specify the headers associated with the request.

Javascript Code to send form data to servers :

filter_none

edit
close

play_arrow

link
brightness_4
code

window.addEventListener('load', ()=>{
        
       const form = document.querySelector('form');
       form.addEventListener('submit', (e)=>{
           //to prevent reload
           e.preventDefault();
           //creates a multipart/form-data object
           let data = new FormData(form);
           axios({
             method  : 'post',
             url : '/',
             data : data,
           })
           .then((res)=>{
             console.log(res);
           })
           .catch((err) => {throw err});
       });
   });

chevron_right


Testing the Axios request with a mock rest API:
Front End Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport"
              content="width=device-width, 
                       initial-scale=1.0" />
        <script src=
                integrity=
"sha512-VZ6m0F78+yo3sbu48gElK4irv2dzPoep8oo9LEjxviigcnnnNvnTOJRSrIhuFk68FMLOpiNz+T77nNY89rnWDg==" 
                crossorigin="anonymous"></script>
        <title>Document</title>
    </head>
    <body>
        <h3 style="color: green; font-size: 25px;">
            Geeks For Geeks
        </h3>
        <form>
            <input name="first-name" /><br />
            <input name="last-name" /><br />
            <input name="address" /><br />
            <button type="submit">Submit</button>
        </form>
  
        <script type="text/javascript">
            window.addEventListener("load", () => {
                const form = document.querySelector("form");
                form.addEventListener("submit", (e) => {
                    e.preventDefault();
                    let data = new FormData(form);
                    console.log(data);
                    axios({
                        method: "post",
                        url: "/",
                        data: data,
                    })
                        .then((res) => {
                            console.log(res);
                        })
                        .catch((err) => {
                            throw err;
                        });
                });
            });
        </script>
    </body>
</html>

chevron_right


Code for the Node.js based mock REST API:

filter_none

edit
close

play_arrow

link
brightness_4
code

const express = require('express');
const formidable = require('express-formidable');
  
const app = express();
  
app.use(express.static(__dirname+'/index.html'));
app.use(formidable());
  
app.get('/', (req, res)=>{
    res.sendFile(__dirname+'/index.html');
});
  
app.post('/', (req, res)=>{
      
    console.log(JSON.stringify(req.fields));
});
  
app.listen('3000', ()=>{
    console.log('listening to port');
  
});

chevron_right


Sample Request Data:

Output in console:

{"first-name":"Geeks", "last-name":"Geeks", "address":"Noida"}

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.