vue Element Ui Upload 上传 点击一个按钮,选择多个文件后直接上传,使用防抖解决多次上传的问题。

问题:

在使用Element Ui Upload 上传文件时,选择多个文件上传时,on-change事件会一个一个返回上传的文件,导致前端不知道什么时候可以拿到全部上传的文件,再一起调后台接口。

解决方法:

上传文件后,自动把文件传给后台,这里做了一个防抖,等待500ms后在传给后台

代码实现:

<el-upload class="upload-demo" ref="enclosureUpload" accept=".docx" :file-list="fileList" action multiple :limit="7"

:show-file-list="false" :auto-upload="false" :on-change="handleFileChange"

:on-exceed="handleExceed" >

<el-button type="info" size="small" plain round >

上传

</el-button>

</el-upload>

// 文件超出个数限制时的钩子

handleExceed (files, fileList) {

this.message.warning(\`限制选择7个文件,本次选择了 {files.length} 个文件`);

},

// 上传附件 过滤重复

filterRepetition (arr) {

let arr1 = []; //存id

let newArr = []; //存新数组

for (let i in arr) {

if (arr1.indexOf(arr[i].name) == -1) {

arr1.push(arr[i].name);

newArr.push(arr[i]);

}

}

return newArr;

},

// 修改 存放要上传的文件列表

handleFileChange (file, fileList) {

let arr = this.filterRepetition(fileList);

if (arr.length !== fileList.length) {

this.$message("上传重复文件,已过滤重复文件");

}

this.fileList = arr;

// 上传文件后,自动把文件传给后台,这里做了一个防抖,等待500ms后在传给后台

this.debounce(this.submitUpload, 500);

},

// element上传多个文件时,会把每个文件做个单独请求

// 这里的方法是请求最后一次

debounce (fn, waits) {

if (this.timer) {

clearTimeout(this.timer);

this.timer = null;

}

this.timer = setTimeout(() => {

fn.apply(this, arguments); // 把参数传进去

}, waits);

},

// 确定

async submitUpload () {

if (this.fileList.length === 0) {

this.$message.success("请上传文件");

return;

}

let formData = new FormData(); // 用FormData存放上传文件

this.fileList.forEach((file) => {

formData.append("file", file.raw);

});

// 确定上传 把在上传列表里的文件 合并到formData里面传给后台

let res = await importXlsx(formData);

this.fileList = []

this.$message.success('上传成功')

}

相关推荐
崔庆才丨静觅20 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606121 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了21 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅21 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅21 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅1 天前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment1 天前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅1 天前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊1 天前
jwt介绍
前端
爱敲代码的小鱼1 天前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax