Vue JS 2 Post Multipart Form Data Tutorial

Last updated on: by Digamber
In this tutorial, we are going to learn how to post multipart form data to web server in Vue 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:

cd vue-post-multipart-form-data

To remove multi-word error warning, add the following code in vue.config.js file.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

Node.js Gatsby error – “digital envelope routines::unsupported …”

Error: digital envelope routines::unsupported
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

To remove above error for invoking the app, make sure to update the "scripts": [] array in package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

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.

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('API GOES HERE', 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.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.