Vue 2 Tutorial- How To Build Image Preview Vue 2 Component example

In this Vue 2 tutorial, we will learn how to show an image preview before it gets uploaded to the server in Vue.js.

Image Preview in Vue.js Example

Learn To Upload Single & Multiple Images In Vue With Node & Express

While developing an app, we really want our users to have a positive and good experience in our web and mobile app. This can only be accomplished if the user can see a preview of the image before he wants to upload or send it to the webserver.

The image preview is an important feature that makes our users view a preview of his uploaded image.

 

So, in this tutorial, we will learn to create a custom image preview feature in a Vue application. However, there are plenty of plugins available that can allow us to handle image previews in Vue within minutes.

 

Let’s follow the step-by-step implementation of Uploading Single and Multiple Images in Vue:

Step 1- Initializing Vue Project

First of all, we have to set up a basic Vue project. For this, we will install the Vue project using Vue CLI by running the given command:

vue create vue-image-preview

Next, we have to get inside the project:

cd vue-image-preview

 

Error: digital envelope routines::unsupported
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

 


To remove the above error for invoking the app, do remember to update the “scripts”: [] array in the package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

 

Then, we have to add the given dependencies in the Vue project:

npm install sass-loader node-sass

Step 2- Create Image Preview Component

Here, we will create components/FilePreview.vue file. In this component, we will be writing code that will show us the instant image preview in Vue.

Then, we open the FilePreview.vue file and add the Vue template to it.

In the Vue template, we defined the HTML tags. The imagePreviewWrapper div will receive the image link, and the 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>

Further, we add the below 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 the file input.

inside the pickFile() function, we are taking the help of FileReader web API and this API will help us choose the file and convert it to dataURL using the readAsDataURL method.

 

Now, 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 a little bit of style to 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>

Below 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>

Afterward, we move on to App.vue file and insert the following code into the file:

<template>
  <div id="app">
    <FilePreview />
  </div>
</template>
<script>
import FilePreview from "./components/FilePreview";
export default {
  name: "App",
  components: {
    FilePreview,
  },
};
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

Finally, we can start the Vue project:

npm run serve

 

Conclusion

So, we have reached the end of this Vue tutorial, in which we have learned to show an image preview before it gets uploaded to the server in Vue.js app.

 

Thanks

Leave a Reply

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