Showing a preview of an image before uploading is the really cool feature which improves UX. In this article, I want to share with the code which shows all file details before uploading. My code is created in Vue, but I think reading of it should be enough easy for everyone who knows basic JS.
<template>
<div>
<form method="post">
<input
type="file"
name="files"
multiple
v-on:change="handleFile"/>
</form>
<h1>Files</h1>
<div class="s-flex -column">
<div
v-for="(file, index) in files"
class="s-flex -row -center">
<img
v-if="isImage(file)"
:src="fileUrl(file)"
width="50"
/>
<div>
{{ file.name }}
</div>
<div>
{{ file.size * 1024 }} KB
</div>
<div>
{{ file.type }}
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const files = ref([])
const handleFile = (e) => {
const newFiles = e.target.files || e.dataTransfer.files
files.value = files.value.concat(Array.from(newFiles))
}
const isImage = (file) => {
return file.type.includes('image')
}
const fileUrl = (file) => {
return URL.createObjectURL(file)
}
</script>
<style>
.s-flex {
display:flex;
}
.s-flex.-row{
flex-direction: row;
}
.s-flex.-column{
flex-direction: column;
}
.s-flex.-center{
align-items: center;
}
</style>
The most important part of the code is handleFile()
. This function handles files which were uploaded and attaches them to files
. In lines 12-30, the code shows all file details. You can test my code online on Vue SFC Playground.