
Posted on • Originally published atraymondcamden.com on
Vue Quick Shot - Image Upload Previews
Welcome to the fourth entry of my Vue Quick Shots. Be sure to check outpart one,part two, andpart 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:
<divid="app"v-cloak><p><inputtype="file"accept="image/*"ref="myFile"@change="previewFile"></p><imgv-if="imgsrc":src="imgsrc"class="imgpreview"></div>
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 #"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">
MypreviewFile
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 aFileReader
object to read in the data and create a data url. This then gets assigned toimgsrc
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!