这篇文章为您详细说了一个单文件上传前端组件,基于 Vue 3 与 ElementPlus 开发。话说回来,它专注解决开发者在文件上传过程中遇到的常见痛点:上传速度慢、文件类型与大小限制不够灵活、提示信息不够友好、清空/覆盖文件操作繁琐等。
使用者痛点一览
-
**文件类型不受控**:默认上传所有文件,导致后端处理错误。
-
**最大文件大小限制缺失**:使用者容易误上传过大文件,浪费流量。不过,
-
**自定义触发器缺少**:无法根据业务场景自定义按钮或文字。不过,
-
**错误提示模糊**:程序弹窗往往信息不完整。难以定位问题,
-
**覆盖/清空操作繁琐**:每次都要手动重置表单或页面。
主要功能概览
-
文件覆盖一次只能选择一个文件,自动覆盖之前的选择。
-
指定可接受的文件类型
-
设置最大文件大小
-
自定义触发元素
-
自定义错误/提示内容
组件源码
\t\t
\t\t
\t\t
\t\t\t
\t\t\t\t
`
`
支持的最大文件大小:{{ props.maxFileSize.size }}{{ props.maxFileSize.unit }}
slot name='tip'/>
script setup lang='ts'
import { ref } from 'vue';import { ElNotification,genFileId } from 'element-plus';import type { UploadInstance,UploadProps。UploadRawFile,UploadFile } from 'element-plus';type SizeUnit = 'KB' | 'MB' | 'GB';const props = defineProps<<{ accept?: string maxFileSize?: { size: number unit: SizeUnit } }>;const emit = defineEmits<<{ : void }>;defineExpose({
clearFile {
upload.value!.clearFiles,if {
tempFile = undefined;emit,}
},});不过,const upload = ref<;let tempFile: UploadFile | undefined;// 覆盖前一个文件
const handleExceed: UploadProps = files => {
upload.value!老实说,.clearFiles;const file = files as UploadRawFile;file.uid = genFileId;upload.value!不过,.handleStart;},function handleChange {
if ) {
rollback;// 文件不合法时回退
return;}
tempFile = uploadFile;emit,}
function isValidFile {
// 类型校验
if ) {
ElNotification.error;return false;}
// 大小校验
if ) {
ElNotification.error({
至于title。'非法大小',message:`超过限制 ${props.maxFileSize?不过,.size}${props.maxFileSize?
.unit}`,position:'top-right'
});return false;}
return true;}
function rollback {
if { upload.value!.clearFiles,upload.value!老实说,.handleStart;}
else { upload.value!.clearFiles,}
}
function handleRemove { temp=undefined;emit,}
const acceptTypes= props.accept?.split,function isValidType{
ifreturn true;const ext='.'+file.name.split.pop;return acceptTypes.includes;}
function isValidSize{
ifreturn true;}
...
style scoped>
API介绍
属性
| 属性名 | 说明 | 类型 | 默认值 |
| Props |
| 接受的图片格式列表。例如`.jpg,.png`;若不传则无限制, |
| max-file-size |
| 对象形如 `{ size:number unit:'KB'|'MB'|'GB'}`;若未传则无限制,话说回来, |
| 事件 |
| file-change |
| 插槽 |
| default - 用于放置触发选择框的按钮或文字。 |
| tip - 用于展示自定义提示信息。 |
| 暴露的方法 |
| clear-file - 清空当前已选中的文件。 |
使用示例
template>
Single-file-upload ref=\"fileUploadRef\" accept=\".md。.txt\" :max-file-size={size:50 unit:'KB'} @file-change=\"handle-file-change\"
style=\"width:\200px\">
"选择文件",...
script setup lang='ts'\>
import Single-file-upload from '@/components/base/Single-file-upload.vue';const fileUploadRef = ref;function handle-file-change{
console.log;}
// 提交表单时使用
async function submitForm{
const formData=new FormData;formData.append);await axios.post;console.log,// 清空状态
fileUploadRef.clear-file;}
<\/script>'>
*上述代码演示了如何:
-
accept=".md,.txt" – 限定只允许 Markdown 与文本。
-
max-file-size="{ size:50,unit:'KB'}" – 最大尺寸仅为 50 KB。
-
@file-change – 接收并处理选中文件事件。
-
clear-file – 提交完毕后立即清除旧数据,避免重复提交。
*通过此组件,即可在几行代码内完成安全、友好的单个文件上传流程。其实,
>