File uploads
This is an example of how experience can work against you: some time ago implementing a file upload component with custom styles was quite complex.
For this reason, I've always used a library for that purpose.
But last time, the idiosyncrasies of the library made integration with our project too difficult. So I opted for a custom implementation and what was my surprise: it is extremely simple.
Show me the code #
Basically, implement a custom upload button implies having a hidden file button with a label linked to it. This is because lables linked to components acts as trigger of them.
There are several ways to link labels and components, but looks like the safer is using the for
property to the id
property of the component:
<template>
<label for="fileInput">
<img src="/upload-file.png" />
</label>
<input
id="fileInput"
ref="upload"
type="file"
accept="image/*"
name="files"
style="display: none"
@change="handleFileInputChanged"
/>
</template>
<script>
export default {
...
handleFileInputChanged(event) {
this.inputFile = Array.from(event.target.files)[0]
}
}
</script>
This is an example of a single image input component.
Display the upload image #
Once you have the file (in this case, the image) you can show it back. As easy of creating a file url and
<template>
<img :src="uploadedImageUrl">
</template>
<script>
export default {
...
uploadImageUrl() {
return URL.createObjectURL(this.inputFile);
}
}
References: