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

3.1k views Asked by At

I am working on displaying/previewing an image after uploading it. I am trying to upload an image and then make an axios/AJAX call.

Please find the code below:

HTML code:

        <span>User Name</span>
           <input v-model="person_name" placeholder="Edit Me">
           <br>
           
        <!--Uploading pic -->
        <span>Display Pic</span>
           <input type="file" name="file" />
           <br>

        <!-- I want to display this uploaded pic here, before submitting the form -->

        <!-- Skipping the code to submit (button code, etc) the form --> 
          

Javascript Code --> AJAX/FETCH call to the API

            var formData = new FormData();
            var fileField = document.querySelector("input[type='file']");

            formData.append('username', this.person_name);
            
            formData.append('File', fileField.files[0]); // getting the file attached
            
            const body = formData;

            const init = {
                method: 'POST',
                body
            };

            fetch('http://..xyz....com', init)
                .then((response) => {
                return response.json(); // or .text() or .blob() ...
            })
                .then((text) => {
                // text is the response body
            })
                .catch((e) => {
                // error in e.message
            });
        },

How do I display or preview the picture/photo as an avatar or something after uploading the pic.

1

There are 1 answers

0
Mohammad Basit On BEST ANSWER

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;
  }
}