Vue Image Preview Tutorial – Image Preview in Vue.js Example

Last updated on by Digamber
If you want to show image preview before it gets uploaded to the server in Vue.js than you are at the right place.

Image Preview in Vue.js Example

If you are a beginner in Vue application development, then you must check out our previously written tutorials on image uploading.

Upload Single & Multiple Images in Vue with Node & Express.

A user always wants to see a preview of the image before he wants to upload or send it to the webserver. Image preview is a process in which a user views a preview of his uploaded image.

If you don’t provide this feature in your web and mobile application, it leads a user to a negative user experience. A user considers your app to be less effective in terms of usability.

In this tutorial, we are going to create a custom image preview feature in a vue application. However, there are plenty of plugins available that can allow you to handle image preview in vue within minutes.

Initializing Vue Project

Let’s set up the environment by setting up a basic vue project. We need to install the vue project using vue CLI, run the following command.

vue create vue-image-preview

Get inside the project:

cd vue-image-preview

Start the vue project:

npm run serve

Create Image Preview Component

Now, we have to create components/filePreview.vue file. In this component, we will be writing code that will show us the instant image preview in vue.

Open the filePreview.vue file and add the vue template in it.

In the vue template, we defined the HTML tags: The imagePreviewWrapper div will receive the image link, and image will be added as a background image via the previewImage data variable. The selectImage property corresponds to the click event.

A user will communicate with <input type="file">. This will work as a file picker, and we will choose a file and process the image using the FileReader API.

<template>
  <div>
    <div
      class="imagePreviewWrapper"
      :style="{ 'background-image': `url(${previewImage})` }"
      @click="selectImage">
    </div>

    <input
      ref="fileInput"
      type="file"
      @input="pickFile">
  </div>
</template>

Next, add the following code in the filePreview.vue component.

<script>
export default {
  data() {
      return {
        previewImage: null
      };
    },
  methods: {
      selectImage () {
          this.$refs.fileInput.click()
      },
      pickFile () {
        let input = this.$refs.fileInput
        let file = input.files
        if (file && file[0]) {
          let reader = new FileReader
          reader.onload = e => {
            this.previewImage = e.target.result
          }
          reader.readAsDataURL(file[0])
          this.$emit('input', file[0])
        }
      }
  }
}
</script>

The previewImage holds the image data or preview url.

The pickFile method triggers when the user selects the image using file input.

Inside the pickFile() function, we are taking the help of FileReader web API, and This API will help us choosing the file and convert it to DataURL using the readAsDataURL method.

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file’s data as a base64 encoded string.
MDN Docs

We will add the base64 data as a background image url to show the image preview. However, we are not going to store the base64 URL on the server.

Finally, we need to add the little bit of style for the image preview block at the bottom of the vue component:

<style scoped lang="scss">
.imagePreviewWrapper {
    width: 250px;
    height: 250px;
    display: block;
    cursor: pointer;
    margin: 0 auto 30px;
    background-size: cover;
    background-position: center center;
}
</style>

Here is the final code that directly goes to filePreview.vue component.

<template>
  <div>
    <div
      class="imagePreviewWrapper"
      :style="{ 'background-image': `url(${previewImage})` }"
      @click="selectImage">
    </div>

    <input
      ref="fileInput"
      type="file"
      @input="pickFile">
  </div>
</template>

<script>
export default {
  data() {
      return {
        previewImage: null
      };
    },
  methods: {
      selectImage () {
          this.$refs.fileInput.click()
      },
      pickFile () {
        let input = this.$refs.fileInput
        let file = input.files
        if (file && file[0]) {
          let reader = new FileReader
          reader.onload = e => {
            this.previewImage = e.target.result
          }
          reader.readAsDataURL(file[0])
          this.$emit('input', file[0])
        }
      }
  }
}
</script>

<style scoped lang="scss">
.imagePreviewWrapper {
    width: 250px;
    height: 250px;
    display: block;
    cursor: pointer;
    margin: 0 auto 30px;
    background-size: cover;
    background-position: center center;
}
</style>

You can find out the complete code for this tutorial on this GitHub repository.