DEV Community

Cover image for Image Preview Before Upload In VueJS Project
Lakh Bawa
Lakh Bawa

Posted on

Image Preview Before Upload In VueJS Project

Hi Everyone, Hope you are doing well and staying safe,

Today I will be sharing with you the small snippet of code that can help you to preview the image the user before it gets uploaded

Create a Directory and File.

mixins/ImagePreviewMixin.vue



<script>
export default {
  data() {
    return {
      imagePreviewURL: null,
    }
  },
  methods: {
    onFileChange(payload) {
      //const file = payload.target.files[0]; // use it in case of normal HTML input
      const file = payload; // in case vuetify file input
      if (file) {
        this.imagePreviewURL = URL.createObjectURL(file);
        URL.revokeObjectURL(file); // free memory
      } else {
        this.imagePreviewURL =  null
      }
    }
  },
}
</script>



Enter fullscreen mode Exit fullscreen mode

We have created the Mixin and we can import that mixin into component

for example

components/UpdateUserAvatar.vue



<script>
import ImagePreviewMixin from "@/mixins/ImagePreviewMixin";

export default {

  mixins: [ImagePreviewMixin],
}
</script>

<template><div>
Using Vuetify
<v-file-input
                    v-model="avatarImage"

                    label="Image"
                    required
                    @change="onFileChange"
                  ></v-file-input>

/* IN case of Normal HTML Input
<input
                    v-model="avatarImage"
                   type="file"
                    label="Image"
                    required
                    @change="onFileChange"
                  ></v-file-input>
*/

<img
                    v-if="imagePreviewURL"
                    :src="imagePreviewURL"
                    alt=""
                    style="max-width: 100%;width: 250px; object-fit: cover"
                  />
</div></template>


Enter fullscreen mode Exit fullscreen mode

Alt Text

Top comments (3)

Collapse
 
jayanika profile image
Jayanika Chandrapriya

any preview?

Collapse
 
bawa_geek profile image
Lakh Bawa

Updated

Collapse
 
cedric_i profile image
Cedric Isubol

If someone encounters error try my code : dev.to/cedric_i/vue-js-image-previ...