Categories
JavaScript Answers Vue Vue Answers

How to upload an image in Vue.js?

Spread the love

Sometimes, we want to upload an image in Vue.js.

In this article, we’ll look at how to upload an image in Vue.js.

How to upload an image in Vue.js?

To upload an image in Vue.js, we can add a file input.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <p>
      <input type="file" accept="image/*" @change="uploadImage">
      <img :src="previewImage" />
    </p>
  `,
  data: {
    previewImage: undefined
  },
  methods: {
    uploadImage(e) {
      const [image] = e.target.files;
      const reader = new FileReader();
      reader.readAsDataURL(image);
      reader.onload = e => {
        this.previewImage = e.target.result;
        console.log(this.previewImage);
      };
    }
  }
})

We add the file input and img element to preview the image.

Then we set the change event handler of the input to uploadImage.

In uploadImage, we get the first selected file from e.target.files.

Then we create a new FileReader instance and call readAsDataURL with image to read it into a base64 string.

Then we set this.previewImage to `e.target.result, which has the base64 image string.

As a result, when we select an image with the file input, we see the image displayed.

Conclusion

To upload an image in Vue.js, we can add a file input.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *