前端循环下载多个PDF,数量丢失处理

项目中导出PDF少则一两个,多则上百,当数量十几个的时候偶尔会出现数量变少的情况,这是因为浏览器跟不上网速导致,可以使用延时的方式解决

//主要代码
const waitTime = async (milliseconds) => await new Promise((resolve) => setTimeout(resolve, milliseconds));
await waitTime(500);

详细代码:

//oss下载方法
let OSS = require('ali-oss');
const path = require("path")
const oss = new OSS({
  region: "oss-cn-shanghai",
  accessKeyId: accessKeyId,
  accessKeySecret: accessKeySecret,
  bucket: bucketName
});
  
async function put (fileName, file) {
  try {
    const result = await oss.put(fileName, file);
    // console.log(result)
    return `https://bucketName.oss-cn-shanghai.aliyuncs.com/` + result.name;
  } catch (e) {
    console.log(e);
  }
}

async function getFileBuffer (name) {
  try {
    return oss.get(name);
  } catch (e) {
    console.log(e);
  }
}

export {
  put ,
  getFileBuffer
}

//转buffer
export function saveFromBuffer(buffer, fileName,fileNameNew) {
  const blob = new Blob([buffer], {
    type: 'application/octet-stream'
  })
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
    window.navigator.msSaveBlob(blob, decodeURI(fileName))
  } else {
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob)
    // 创建a标签,用于跳转至下载链接
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    const suffix = fileName.substring(fileName.lastIndexOf('.') + 1)
    //如果是pdf
    if (suffix == 'pdf') {
      tempLink.download = `${fileNameNew}.pdf`
      tempLink.setAttribute('download', decodeURI(tempLink.download))
    } else {
      tempLink.setAttribute('download', decodeURI(fileName))
    }
    // 兼容:某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 挂载a标签
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL)
  }
}

   //确定导出
    async exportSubmit() {
      this.exposeLoading = true;
      let params = {
        operation: "deriveExcel",
        operator: this.$store.state.user.name, 
        dataType: "is_check_normal", 
        derive_type: this.formInline.region 
      };
      if (this.tableData.length > 0) {
        try {
          let res = await this.$api.deriveFn(params);
          if (res.successful == true || res.successful == "true") {
          	  //延时写在for循环上方
              const waitTime = async (milliseconds) => await new Promise((resolve) => setTimeout(resolve, milliseconds));
              let nums = 0;
              for (let i = 0; i <= res.data?.pdfDocs.length; i++) {
                let name = res.data.pdfDocs[i].substring(
                  res.data.pdfDocs[i].lastIndexOf("/") + 1
                );
                let nameNew = res.data.pdfName[i]
                try {
                  const result = await getFileBuffer(res.data.pdfDocs[i]);
                  //转Buffer
                  this.$api.saveFromBuffer(result.content, name,res.data.pdfName[i]);
                  //调用写在转buffer下方
                  await waitTime(500);
                  if(i == res.data?.pdfDocs.length -1){
                    this.$message({
                      type: "success",
                      message: "导出成功!"
                    });
                  }
                } catch (error) {
	                nums += 1;
	                console.log(nums, "有失败文件");
	                if (i == res.data?.excelPDF.length - 1 && nums > 0) {
	                  this.$message({
	                    type: "error",
	                    message: `导出过程中有${nums}个文件失败`,
	                  });
	                }
	              }
       	      }
          }
          this.exposeLoading = false;
          this.exportLayer = false;
        } catch (error) {
          this.exposeLoading = false;
          this.exportLayer = false;
        }
      } else {
        this.$message({
          type: "error",
          message: "暂无数据导出~"
        });
        this.exposeLoading = false;
        this.exportLayer = false;
      }
    },

参考: https://blog.csdn.net/feyehong/article/details/124974601

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值