隐藏 input:file ,在页面创建 button 和 span 用于展示文件上传按钮和文件上传文本,在点击 button 时调用 input:file 的点击上传事件触发文件上传。
创建的 button 和 span 即可进行自定义样式
代码
<template>
<div id="app">
<input type="file" ref="inputfile" @change="fileChange" />
<button @click="fileClick">选择上传文件</button>
<span>{{ text }}</span>
</div>
</template>
<script>
export default {
data() {
return {
text: "请选择要上传的文件",
};
},
methods: {
// button 点击触发 input:file 点击
fileClick() {
this.$refs.inputfile.click();
},
// input:file 文件上传
fileChange(res) {
const file = res.target.files[0]; // 获取上传文件
const fileType = ["jpg", "png"]; // 要求文件格式
const fileSize = 2; // 要求文件大小
const { name } = file;
const nameSplit = name.split("."); // 获取上传文件后缀名
const suffix = nameSplit[nameSplit.length - 1].toLocaleLowerCase();
if (!fileType.includes(suffix)) {
alert(`文件类型应为${fileType.join("、")}`);
return;
}
const { size } = file;
const isLimitSize = size / 1024 / 1024 < fileSize; // 判断上传文件大小
if (!isLimitSize) {
alert(`文件大小应小于${fileSize}M`);
return;
}
this.text = file.name;
console.log("取得上传的文件", size / 1024 / 1024, file);
},
},
};
</script>
<style>
input {
display: none;
}
button {
width: 100px;
height: 40px;
border-radius: 10px;
background: pink;
}
span {
margin-left: 20px;
font-style: italic;
color: red;
}
</style>
效果图