• 前端循环下载多个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
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    //转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)
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
       //确定导出
        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;
          }
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

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

  • 相关阅读:
    含文档+PPT+源码等]精品springboot核酸检测管理系统vue[包运行成功]程序设计源码计算机毕设
    gitcode代码仓库的基本使用
    @vitejs/plugin-legacy 为你的 Vite 项目提供对旧版浏览器的支持
    JDK安装
    王学岗音视频开发(一)—————配置NDK开发环境
    创建和删除目录( mkdir函数 和 rmdir函数 )
    Spring Security Taglibs 简介
    LocalDate的用法
    Linux sed命令笔记 221012
    Qt 信号和槽
  • 原文地址:https://blog.csdn.net/dreamy_wx/article/details/126990458