最近接到了一个需求,需要在PC页面上循环调用接口上传图片,最多支持200张。
这可把只会复制粘贴的我给难到了,赶紧理解需求学习学习。
1、分析需求
- 按钮点击弹出会话框。
- 点击上传组件Ctrl + A 全选所有图片(不超过200张,每张大小不超过1M)。
- 点击确定上传循环调用接口,一次请求上传一张图片。
需求1、2 Element Ui 已经给我们提供了一个 Upload 上传组件,只需要拿过来用即可。文件类型及验证同事写了,直接拿过来用。
需求3就自己写吧
2、编写代码
const loading = this.$loading({
lock: true,
text: '正在上传...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
// function this指向Window,得改成Vue实例对象
let this_ = this
// 异步改'同步'调用接口
async function idUpload(){
// forEach等循环不能处理异步代码,换成for形式
for (var index = 0; index < this_.file.length; index++) {
if(index <= this_.file.length){
let formData = new FormData();
formData.append("file", this_.file[index]);
await postSettleInfoUploadBb(formData).then(res => {
// 最后一个图片上传成功后执行
if(index == this_.file.length -1){
if(res.code == 200){
loading.close();
this_.visible = false;
this_.msgSuccess(res.data);
this_.$router.replace({
path: "/redirect" + this_.$route.fullPath,
});
}
}
}).catch(err => {
loading.close();
// this_.msgError(`第 ${index + 1} 张图片上传失败`)
})
}
}
}
idUpload();
参考文章
- 每天在使用的await,为什么不能用在forEach中?https://blog.csdn.net/qianyu6200430/article/details/108656286
- vue循环请求同一个接口,等接口返回数据之后在进行下次循环,同步调用api接口方式https://blog.csdn.net/weixin_40476233/article/details/121292970