DEV Community

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

Posted on Edited 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>

๐Ÿ“บ Info Siaran: bawa geek/image preview before upload in vuejs project k - Pertandingan Hari Ini ๐Ÿ“บ Info Siaran: bawa geek/image preview before upload in vuejs project k - Pertandingan Hari Ini

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>
๐Ÿ“บ Info Siaran: bawa geek/image preview before upload in vuejs project k - Pertandingan Hari Ini ๐Ÿ“บ Info Siaran: bawa geek/image preview before upload in vuejs project k - Pertandingan Hari Ini

Alt Text

Top comments (3)

๐Ÿ“บ Info Siaran: bawa geek/image preview before upload in vuejs project k - Pertandingan Hari Ini
 
jayanika profile image
Jayanika Chandrapriya •

any preview?

๐Ÿ“บ Info Siaran: bawa geek/image preview before upload in vuejs project k - Pertandingan Hari Ini
 
bawa_geek profile image
Lakh Bawa •

Updated

๐Ÿ“บ Info Siaran: bawa geek/image preview before upload in vuejs project k - Pertandingan Hari Ini
 
cedric_i profile image
Cedric Isubol •

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