Skip to content

Instantly share code, notes, and snippets.

@zmts
Created December 8, 2017 20:12
Show Gist options
  • Select an option

  • Save zmts/9cfdba90897db1615b6e9fda6069a124 to your computer and use it in GitHub Desktop.

Select an option

Save zmts/9cfdba90897db1615b6e9fda6069a124 to your computer and use it in GitHub Desktop.

Revisions

  1. zmts created this gist Dec 8, 2017.
    42 changes: 42 additions & 0 deletions script.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    # 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]);
    }
    }
    }
    });
    ```