One data grid for JavaScript, React, Vue & Angular. Sorting, filtering, virtualization, pinning, and CSV export included. Early access $199 $349 → [Get it now]

How to preview images before upload in Vue

Showing image previews before upload greatly improves user experience by letting users verify their selection before submitting. As the creator of CoreUI, I’ve built this feature into numerous profile editors and content management systems. The most effective solution is to use the FileReader API to read the selected file and create a data URL for display. This approach works entirely in the browser without requiring a server roundtrip.

Use FileReader to read the selected image file and display it as a preview.

<template>
  <div>
    <input type='file' @change='previewImage' accept='image/*' />
    <img v-if='imageUrl' :src='imageUrl' alt='Preview' />
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const imageUrl = ref('')

    const previewImage = (event) => {
      const file = event.target.files[0]
      if (!file) return

      const reader = new FileReader()
      reader.onload = (e) => {
        imageUrl.value = e.target.result
      }
      reader.readAsDataURL(file)
    }

    return { imageUrl, previewImage }
  }
}
</script>

The FileReader API reads the selected image file and converts it to a base64-encoded data URL. The readAsDataURL() method triggers the onload event when complete, providing the result as e.target.result. This data URL is stored in a ref and bound to an <img> element’s src attribute. The v-if directive ensures the image only displays when a file is selected, and the accept='image/*' attribute limits file selection to images only.

Best Practice Note

This is the same image preview approach we use in CoreUI Vue components for profile uploads and galleries. For better performance with large images, consider validating file size before reading and add error handling for unsupported file types. You can also revoke the object URL with URL.revokeObjectURL() when done to free memory.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What is Double Question Mark in JavaScript?
What is Double Question Mark in JavaScript?

How to declare the optional function parameters in JavaScript?
How to declare the optional function parameters in JavaScript?

How to Merge Objects in JavaScript
How to Merge Objects in JavaScript

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript