DEV Community

Cover image for Vue Quick Shot - Image Upload Previews
Raymond Camden
Raymond Camden

Posted on • Originally published at raymondcamden.com on

Vue Quick Shot - Image Upload Previews

Welcome to the fourth entry of my Vue Quick Shots. Be sure to check out part one, part two, and part three. Today's entry is slightly more complex than the previous ones - adding an image preview to file upload controls.

This is something I've covered before, but not with Vue.js. Let's start with the HTML:

<div id="app" v-cloak>
  <p>
  <input type="file" accept="image/*" ref="myFile" @change="previewFile">
  </p>
  <img v-if="imgsrc" :src="imgsrc" class="imgpreview">
</div>

Enter fullscreen mode Exit fullscreen mode

In my input field, pay attention to the attributes:

  • accept="image/* tells the browser to filter files that can be selected to images of any type. However, the user can switch this filter to any file.
  • I then use ref="myFile" so Vue can have access to it. You'll see how in a bit.
  • Finally, I specify the when the file input is changed, it should run the previewFile method.

Below the input field I have an img tag that will display the image when one is selected.

Alright, now let's look at the JavaScript:

const app = new Vue({
  el:'#app',
  data: {
    imgsrc:''
  },
  methods:{
    previewFile() {
      let file = this.$refs.myFile.files[0];
      if(!file || file.type.indexOf('image/') === -1) return;
      let reader = new FileReader();

      reader.onload = e => {
        this.imgsrc = e.target.result;
      }

      reader.readAsDataURL(file);
    }
  }
})

Enter fullscreen mode Exit fullscreen mode

My previewFile method checks the file input field via $refs and looks at the first file available. If there's one, and it's an image, we then use a FileReader object to read in the data and create a data url. This then gets assigned to imgsrc so that the image can render it.

And that's it! Here's a live version you can play with:

I hope you enjoyed this quick shot - only one more to go!

Top comments (0)