[Vuejs]-How to preview/display an image after uploading at the side of the upload button in Vue.js (Element.ui)?

3๐Ÿ‘

โœ…

As far as I understand your question you can preview the uploaded image before sending it to the server. You can attach an @change event listener on your input type='file' to listen to the change event and then access the image uploaded by event.target.files[0]. Then change the src of the img tag with the uploaded image src.

Live Demo Here

You can also send it to server immediately after uploading it in the preview() method or you can use upload button to send it to the server.

Your Vue Template:

<template>
  <div id="app">
    <img id="image" :src="imgSrc" />
    <input type=file @change="preview">
  <div>
    <button @click="upload()">Upload</button>
  </div>
  <div> {{ uploaded }} </div>
  </div>
</template>

Script:

data: () => ({
  imgSrc: '',
  uploaded: ''
}),

methods: {
  preview(e) {
    var pic = document.getElementById('image')
    let imgSrc = URL.createObjectURL(e.target.files[0]);
    this.imgSrc = imgSrc
  },
  upload() {
    this.uploaded = this.imgSrc;
  }
}
๐Ÿ‘คMohammad Basit

Leave a comment