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 with over 11 years of Vue development experience since 2014, 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.



