js循环调用接口上传图片

最近接到了一个需求,需要在PC页面上循环调用接口上传图片,最多支持200张。
这可把只会复制粘贴的我给难到了,赶紧理解需求学习学习。

523025199008020351-2.jpg

1、分析需求

  1. 按钮点击弹出会话框。
  2. 点击上传组件Ctrl + A 全选所有图片(不超过200张,每张大小不超过1M)。
  3. 点击确定上传循环调用接口,一次请求上传一张图片。
    需求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();

参考文章

  1. 每天在使用的await,为什么不能用在forEach中?https://blog.csdn.net/qianyu6200430/article/details/108656286
  2. vue循环请求同一个接口,等接口返回数据之后在进行下次循环,同步调用api接口方式https://blog.csdn.net/weixin_40476233/article/details/121292970
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值