How To Upload Files With Vue

Mar 19, 2021

Using Vue 2 with Axios, you can upload files easily with a few clicks. Using the <input> tag and specifying the type to file, the browser will allow you to select the file to upload from your computer.

Axios can POST FormData instances, which makes it easy to upload files. Once the user has selected a file, you can upload the JavaScript blob by adding it to a FormData instance. Below is an example.


  const app = new Vue({
    data: () => ({images: null}),
    template: `
      <div>
        <input type="file" @change="uploadFile" ref="file">
        <button @click="submitFile">Upload!</button>
      </div>
    `,
    methods: {
      uploadFile() {
        this.Images = this.$refs.file.files[0];
      },
      submitFile() {
        const formData = new FormData();
        formData.append('file', this.Images);
        const headers = { 'Content-Type': 'multipart/form-data' };
        axios.post('https://httpbin.org/post', formData, { headers }).then((res) => {
          res.data.files; // binary representation of the file
          res.status; // HTTP status
        });
      }
    }
  });
  app.$mount("#content");

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials