How to preview an image before it is uploaded with Vue.js?

Sometimes, we want to preview an image before it is uploaded with Vue.js.

In this article, we’ll look at how to preview an image before it is uploaded with Vue.js.

How to preview an image before it is uploaded with Vue.js?

To preview an image before it is uploaded with Vue.js, we can convert the selected image file into a URL and then set the URL as the value of the img element src attribute.

For instance, we write

<template>
  <div id="app">
    <input type="file" @change="onFileChange" />

    <div>
      <img v-if="url" :src="url" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      url: null,
    };
  },
  methods: {
    onFileChange(e) {
      const [file] = e.target.files;
      this.url = URL.createObjectURL(file);
    },
  },
};
</script>

to add a file input and an img element for showing the preview.

Then we add the onFileChange method which is called when we select a file since we have

@change="onFileChange"

Then we get the selected file in the method with e.target.files.

And then we convert the image file to a URL with URL.createObjectURL and assign it to this.url.

Then we set :src to url in the img element to show the selected image file.

Conclusion

To preview an image before it is uploaded with Vue.js, we can convert the selected image file into a URL and then set the URL as the value of the img element src attribute.