preface
As we all know, HTML’s native input tag sets type to File to select files from a web page and upload them
<input id="file-selector" type="file" />
All it takes is one line of code
However, the native style is too ugly to meet our needs. This article will show you how to implement a file upload button of your own
The principle of
The implementation principle is not complicated, just use the display attribute to hide the native input tag, and use another button to call the input tag
implementation
Since we implemented it in VUE, I assume that you have the basics of VUE
<! -- html -->
<input
id="file-selector"
ref="uploadInput"
type="file"
@change="uploadFile"
style="display: none"
/>
<button class="Custom Styles" @click="selectFile">Upload a file</button>
Copy the code
The ID and type attributes are natively owned, and ref is used to retrieve the current input tag. The @change method will only be called if the file is selected and clicked open, but not if the file is clicked cancel
// js.methods: {// Select the file
selectFile() {
this.$refs.uploadInput.click();
},
// Upload the file
uploadFile(e) {
// Get the selected file to upload
const file = e.target.files[0];
// Upload the file. }},Copy the code
This way, you can make your own beautiful file upload buttons