Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

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>
Enter fullscreen modeExit 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 useref="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 thepreviewFile 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">Enter fullscreen modeExit fullscreen mode

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!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Raymond Camden
Raymond Camden is a experienced developer advocate and evangelist. His work focuses on APIs, the web platform, and generative AI. He is the author of multiple books on development and has been activel
  • Location
    Louisiana
  • Work
    API Evangelist at Foxit
  • Joined

More fromRaymond Camden

Using Intl.DurationFormat for Localized Durations
#javascript
Uploading Multiple Files with Fetch
#javascript
Integrating Eleventy with GitHub Flat Data
#eleventy#javascript#staticsites
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp