Vue.Js Post Multipart Form Data using Axios & Express API

Last updated on by Digamber
In this tutorial, we are going to learn how to post multipart form data to web server in Vue.js application using Axios plugin and FormData web API.

To understand this concept, we will create a basic Vue app using Vue CLI. We will use the Bootstrap CSS framework to create the Form to get the values such as user name and user image.

To deal with server requests we will use the Axios library. Since Vue.js is a complaint JavaScript framework for developing high-quality and user-friendly apps. Unfortunately, It doesn’t come with any proper mechanism to make external HTTP calls. Nevertheless, there are many ways through which we can make HTTP requests.

So, to make the Requests to web server we are going to use Axios http client.

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to “multipart/form-data”.
MDN web docs

Initialize the Vue Project

Install the project by using the following command:

vue create vue-post-multipart-form-data

Head over to the project folder:

vue create vue-post-multipart-form-data

Start the app in the browser:

npm run serve

Adding Bootstrap

We are going to take a very simple approach to add the Bootstrap framework in Vue. We will simply add the Bootstrap CDN link in between the <head> tag of the public/index.html file.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh">

Install Axios Package

Run command to install the Axios library in Vue.

# NPM
npm install axios --save


# Yarn
yarn add axios

To use Axios, we directly import it inside the Vue template.

Git Clone Node/Express Backend Server

We have already created the API with Node, Express, MongoDB and Multer. However, you can use your API and you can skip this step if you have your own set of APIs.

Git clone the project in the root of the Vue project.

git clone https://github.com/SinghDigamber/nodejs-file-upload-server.git backend

# Cloning into 'backend'...
# remote: Enumerating objects: 4017, done.
# remote: Counting objects: 100% (4017/4017), done.
# remote: Compressing objects: 100% (2958/2958), done.
# remote: Total 4017 (delta 858), reused 4013 (delta 857), pack-reused 0
# Receiving objects: 100% (4017/4017), 3.98 MiB | 1.14 MiB/s, done.
# Resolving deltas: 100% (858/858), done.
# Checking out files: 100% (3947/3947), done.

Get inside the backend directory, open the terminal window and run the command:

cd backend

npm install

Then, start the mongoDB database.

mongod --config /usr/local/etc/mongod.conf

brew services start mongodb-community@4.2

mongo

Run the nodemon server using the below command:

nodemon

Now, you can check your Node server on: http://localhost:4000/api

  • /api: Users List
  • /api/create-user: Create User

Sending Multipart Form Data in Vue with Axios

Open Vue component file and add place the following code inside of it.

<template>
  <div>
    <div class="container">
        <form @submit.prevent="onSubmit">
            <div class="form-group">
                <input type="file" @change="onFileUpload">
            </div>
            <div class="form-group">
                <input type="text" v-model="name" placeholder="Name" class="form-control">
            </div>
            <div class="form-group">
                <button class="btn btn-primary btn-block btn-lg">Upload File</button>
            </div>
        </form>
    </div>    
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
      return {
         FILE: null,
         name: ''
      };
    },
    methods: {
        onFileUpload (event) {
          this.FILE = event.target.files[0]
        },
        onSubmit() {
          // upload file
          const formData = new FormData()
          formData.append('avatar', this.FILE, this.FILE.name)
          formData.append('name', this.name)
          axios.post('http://localhost:4000/api/create-user', formData, {
          }).then((res) => {
            console.log(res)
          })
        }  
    }

}
</script>

<style scoped lang="scss">
.container {
  max-width: 600px;
}
</style>

First, we created a basic form with file and name values. We are selecting an image using @change="" event, this event allows us to listen to any change in the particular file.

We are getting name-value using a v-model directive.

To upload the file and name value via form data, we declared both the values inside the data property:

We need to declare the two event handler the onFileUpload() and onSubmit() inside the methods life cycle hook in the Vue component.

The formData variable is creating the new FormData() instance, where we are using formData.append() method and setting up file and name value.

Next, to send the multipart form data to the server we called the API inside the axios.post() method.

Post Multipart Form Data using Axios

You can get the full code of this project on this GitHub repository.