el-upload两种不同的上传方式实现分析
作者:西瓜有点饿
el-upload提供了诸多处理,为我们日常开发提供了便利性,同时也存在着一些边界没有处理,这篇文章主要介绍了el-upload两种不同的上传方式实现的相关资料,需要的朋友可以参考下
第一种:选择文件 → 确认上传,两个步骤分离
<el-upload ref="uploadRef" :disabled="loading"
:auto-upload="false"
:on-change="handleFileChange"
:file-list="fileList">
<template #trigger>
<el-button type="primary">选取文件</el-button>
</template>
<template #tip>
<div class="text-xs text-red mt-2">文件格式为xls,xlsx文件,单次最多上传1000条</div>
</template>
<el-button :loading="loading" type="primary" @click="onUpload">确 定</el-button>
</el-upload>
const handleFileChange = (file: any, files: any[]) => {
// 校验文件格式
const ext = file.name.split('.').pop()?.toLowerCase()
if (!['xls', 'xlsx'].includes(ext)) {
message.error('请上传 xls/xlsx 格式的文件')
// 移除不合法的文件
uploadRef.value?.clearFiles()
fileList.value = []
return
}
// 合法文件,更新列表
fileList.value = [file]
}
const onUpload = async () => {
// 检查是否有文件
if (fileList.value.length === 0) {
message.warning('请先选择文件')
return
}
try {
loading.value = true
const params = new FormData()
params.append('file', fileList.value[0].raw)
const res = await UploadAPPListConfig(params)
// 上传成功
if(res.code === 0 && res.data) {
message.success(res.data)
dialogVisible.value = false
emit('success')
}
} finally {
loading.value = false
}
}核心配置:
auto-upload="false":手动控制上传:on-change="handleFileChange":文件选择时触发:file-list="fileList":绑定文件列表独立的触发按钮和上传按钮分离
第二种:选择后自动触发上传
<el-upload
:auto-upload="true"
:show-file-list="false"
:disabled="updLoading"
:before-upload="onBeforeUpload"
:http-request="onUpload" >
<el-button type="primary" :loading="updLoading">选取文件</el-button>
</el-upload>
const onBeforeUpload = (file) => {
// Excel 判断(推荐用扩展名)
const ext = file.name.split('.').pop()?.toLowerCase()
if (!['xls', 'xlsx'].includes(ext)) {
message.error('请上传 xls/xlsx 格式的文件')
return false
}
return true //允许上传
}
const onUpload = async (updFile) => {
try {
updLoading.value = true
const file = updFile.file
const params = new FormData()
params.append('file', file)
const res = await UploadTeleExcel(params)
message.success('上传成功')
// 全部成功才能上传
formData.value.successPhones = res.data.failPhones.length === 0 && res.data.successPhones.length > 0 ? res.data.successPhones: []
} finally {
updLoading.value = false
}
}核心配置:
show-file-list="false":不显示文件列表:before-upload="onBeforeUpload":上传前钩子:http-request="onUpload":自定义上传请求按钮即触发器,选择后自动触发上传
对比总结
| 维度 | 第一种 | 第二种 |
|---|---|---|
| 上传流程 | 两步式(选择→确认) | 一步式(选择即上传) |
| 文件列表 | 显示并管理 | 不显示 |
| 文件状态 | 可缓存、可重置 | 即用即传,无状态 |
| 用户控制 | 用户主动触发上传 | 系统自动触发 |
| 错误处理 | 可重新选择文件 | 需要重新选择 |
| 复杂度 | 较高 | 较低 |
| 适用场景 | 表单提交、批量导入 | 快速上传、单附件 |
到此这篇关于el-upload两种不同的上传方式实现分析的文章就介绍到这了,更多相关el-upload两种上传方式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
