How to upload images in vue.js with axios?

by tressie.damore , in category: Javascript , 5 months ago

How to upload images in vue.js with axios?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 5 months ago

@tressie.damore 

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

  1. Install Axios by running the following command in your Vue.js project directory:
1
npm install axios


  1. Import Axios in your component's JavaScript file:
1
import axios from 'axios';


  1. Create a file input element in your Vue template, allowing users to select an image for upload:
1
<input type="file" ref="fileInput" @change="handleImageUpload" />


  1. Implement the handleImageUpload method in your Vue component, which will be triggered when the user selects an image:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
methods: {
  handleImageUpload(event) {
    const file = event.target.files[0];
    this.uploadFile(file);
  },

  uploadFile(file) {
    const formData = new FormData();
    formData.append('image', file);
    
    axios.post('/upload-url', formData)
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }
}


In the uploadFile method, we create a FormData object and append the selected image file to it. Then, we use Axios to make a POST request to the server's upload URL.

  1. In the above code snippet, replace '/upload-url' with the actual URL where you want to upload the image.


Note: You should configure your server to handle the image upload and store it properly.


That's it! You have now implemented image upload in your Vue.js application using Axios.