Preview an image before it is uploaded VUEjs

76,145

Please keep in mind that a browser cannot display all image types, (eg: a tiff won't work with this method).

There's a few steps:

const vm = new Vue({
  el: '#app',
  data() {
    return {
      url: null,
    }
  },
  methods: {
    onFileChange(e) {
      const file = e.target.files[0];
      this.url = URL.createObjectURL(file);
    }
  }
})
body {
  background-color: #e2e2e2;
}

#app {
  padding: 20px;
}

#preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

#preview img {
  max-width: 100%;
  max-height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <input type="file" @change="onFileChange" />

  <div id="preview">
    <img v-if="url" :src="url" />
  </div>
</div>
Share:
76,145
omiz
Author by

omiz

Updated on March 05, 2020

Comments

  • omiz
    omiz about 4 years

    I know this question has been asked. But I have no idea how to use the code in vuejs. I tried a lot but without any results. I also added my code. Can some one please help me? This is my code. Thanks

    html

    <template>
    <div class="fileUpload">
        <b-container fluid>
    
            <h4>Image Overview</h4>
            <b-button @click="$refs.fileInput.click()" class="btn-right">Select an image</b-button>
    
            <b-table @row-clicked="viewImage" striped hover :items="images" :fields="image_fields"></b-table>
    
            <input style="display: none" ref="fileInput" type="file" @change="fileSelected" enctype="multipart/form-data">
            <b-button variant="success" class="btn-right" @click="uploadImage" method="post">Upload image</b-button>
    
    
        </b-container>
    </div>
    

    js

    <script>
    export default {
        name: 'listImage',
        data() {
            return {
                selectedFile: null,
                images: [],
                image_fields: ['id', 'name'],
                total_images: 1               
            }
        },
        methods: {
            fileSelected(evt) {
                evt.preventDefault()
                console.log(evt);
                this.selectedFile = evt.target.files[0]
            },
            uploadImage() {
                var data = new FormData();
                data.append('image', this.selectedFile, this.selectedFile.data)
                var token = sessionStorage.getItem('token')
                const config = {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                window.API.post('https://110.10.56.10:8000/images/?token=' + token, data, config)
                    .then(response => this.$router.push('/listImage'))
                    .catch((error) => {
                        console.log(JSON.stringify(error))
                    })
            }
        }
    }
    

  • Vladimir Salguero
    Vladimir Salguero over 5 years
    Excellent! very simple and functional!
  • oBo
    oBo about 5 years
    Really nice and short solution! Thanks
  • Khan Shahrukh
    Khan Shahrukh almost 5 years
    this is awesome!
  • Choy
    Choy over 4 years
    I know these codes can works but can you briefly explain a little bit? like the things inside the method. Thx
  • wafs
    wafs over 4 years
    @Choy The onFileChange method takes in an event as the argument, which is triggered by the input whenever a file is changed The input type=file specifically has a files attribute which is the list of files it currently holds. This is a single file input which is why I am limiting it to the first element 0. If no file is there it'll return undefined which clears the image, otherwise it'll point to the user's image. After that, I used URL.createObjectURL() which is native to browsers, to create an Object URL for this local file, which I then use as the src attribute for the image.
  • Franco Maldonado
    Franco Maldonado about 4 years
    Thanks a lot! Very simple and straightforward solution :)
  • longga
    longga about 4 years
    Thank for share, this is very simple and best solution :)
  • Admin
    Admin over 3 years
    <input type="file" @change="onFileChange($event)" />
  • Christoph
    Christoph about 3 years
    Brilliant, thank you!
  • Tijo Titus
    Tijo Titus almost 3 years
    Very simple!!!!
  • redshift
    redshift almost 3 years
    Right after the this.url = URL.createObjectURL(file); line, add this to clear out the browser memory to prevent memory leaks: URL.revokeObjectURL(file)
  • Rheza001
    Rheza001 over 2 years
    does this work on <b-upload /> as well?
  • johnme
    johnme over 2 years
    save my day even in 2022