Skip to content

Instantly share code, notes, and snippets.

@robertstefan
Forked from zmts/script.md
Created May 26, 2021 10:07
Show Gist options
  • Save robertstefan/b5c697d3a40e2f14194b0176b5fa2bb0 to your computer and use it in GitHub Desktop.
Save robertstefan/b5c697d3a40e2f14194b0176b5fa2bb0 to your computer and use it in GitHub Desktop.
Vue.js Preview image file

Preview image file(vue.js)

// https://jsfiddle.net/mani04/5zyozvx8/

new Vue({
    el: '#app',
    template: `
        <div>
            <div class="file-upload-form">
                Upload an image file:
                <input type="file" @change="previewImage" accept="image/*">
            </div>
            <div class="image-preview" v-if="imageData.length > 0">
                <img class="preview" :src="imageData">
            </div>
        </div>
    `,
    data: {
        imageData: ""  // we will store base64 format of image in this string
    },
    methods: {
        previewImage: function(event) {
            // Reference to the DOM input element
            var input = event.target;
            // Ensure that you have a file before attempting to read it
            if (input.files && input.files[0]) {
                // create a new FileReader to read this image and convert to base64 format
                var reader = new FileReader();
                // Define a callback function to run, when FileReader finishes its job
                reader.onload = (e) => {
                    // Note: arrow function used here, so that "this.imageData" refers to the imageData of Vue component
                    // Read image as base64 and set to imageData
                    this.imageData = e.target.result;
                }
                // Start the reader job - read file as a data url (base64 format)
                reader.readAsDataURL(input.files[0]);
            }
        }
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment