How to upload images in vue.js with axios?

by filiberto , in category: Javascript , 5 months ago

How to upload images in vue.js with axios?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 5 months ago

@filiberto 

To upload images in Vue.js with Axios, you can follow these steps:

  1. First, you need to create a form in your Vue component where users can select the image to upload:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
  <div>
    <input type="file" @change="onFileChange">
    <button @click="uploadImage">Upload</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null
    }
  },
  methods: {
    onFileChange(e) {
      this.file = e.target.files[0];
    },
    uploadImage() {
      let formData = new FormData();
      formData.append('image', this.file);

      this.axios.post('http://your-api-endpoint', formData)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
}
</script>


  1. In the above example, we have created a file input and a button in the template. When a user selects an image, the onFileChange method is called to store the selected file in the file data property.
  2. When the user clicks the "Upload" button, the uploadImage method is called. Inside this method, we create a new FormData object and append the selected file to it.
  3. Finally, we make a POST request using Axios to the API endpoint with the FormData object containing the image. The API endpoint should handle the image upload and store it on the server.


Make sure you have Axios installed in your project before using it in your Vue component. You can install Axios with the following command:

1
npm install axios --save


That's it! You should now be able to upload images in Vue.js using Axios.