js 下载docx、zip、excel、pdf文件

下载docx or zip
let api = 'http://172.16.133.206:3000/api/crisps-elec-mid/yk/elec/mid/template/download_template.do?templateIdList=1379369742456244186';

fetch(api, {
  // headers添加验签;验签功能取决于接口否有验签要求,一般只验证token;
  // 若只验证token,只需要在请求拦截器统一设置
  headers: {                                   
    // sign: "4D511B5974D175C1754BFCCABC2803B8", // 验签
    // sysCode: "crisps-contract", // 服务名
    "X-Auth-Token": JSON.parse(sessionStorage.getItem("token"))
  }
}).then(r=>r.blob())
    .then(res=>{  // r就是从后端获取到的文件流
       const href = URL.createObjectURL(res);
       Object.assign(document.createElement('a'), {
        href,
        download: tempArr.length === 1 ? '合同模板.docx' : '合同模板.zip',
       }).click();
       URL.revokeObjectURL(href);
    }
)
打印
  • 没有用window.print()方式(打印的是页面可见的元素);
  • 使用iframe方式,打开一个新窗口,将后端返回的图片写入到窗口中进行打印(后端返回的图片)
print_contract({ fileId: this.id }).then((data) => {    // 后端返回得是base64位的图片数组
          const iframe = document.createElement('iframe');

          iframe.onload = function () {
            iframe.contentWindow.document.write(
              data
                .map((item) => {
                  return ``;
                })
                .join(''),
            );
            setTimeout(() => {
              iframe.contentWindow.print();    // 直接打印会空白,利用一点间隙时间
            }, 100);
          };
          iframe.hidden = true;
          document.body.appendChild(iframe);
        }).catch((err) => { });
利用a标签下载image, excel, pdf等
function downLoad(data){
  try {
    let blobObj = await fetch(data.filePath).then((fileStreat) => fileStreat.blob());  // 后端返回二进制文件流
    let blobUrl = window.URL.createObjectURL(blobObj);
  
    const a = document.createElement("a");
    a.download = data.fileName || (new Date().getTime() + '.pdf');
    a.href = blobUrl;
    a.click();
    URL.revokeObjectURL(blobUrl);
  } catch (err) {
    console.log("err:", err);
  }
}
利用canvase重绘图片
async function canvasDrawImg(item){
    let blob = await new Promise((resolve,reject)=>{
        let img = new Image();
        img.src = item.filepath;
        // img.crossOrigin = 'anonymous';
        console.log(2222)
        img.onload = ()=>{
          console.log(3333)
          const cvs = document.createElement("canvas");
          cvs.width = img.width;
          cvs.height = img.height;
          const ctx = cvs.getContext("2d");
          ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
          document.body.removeChild(img);

          cvs.toBlob(resolve, "image/png");
        }
        img.onerror = reject
        document.body.appendChild(img);
      });
      
      let blobUrl = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.download = item.filename;
      a.href = blobUrl;
      a.click();
      URL.revokeObjectURL(blobUrl);
}

你可能感兴趣的:(js 下载docx、zip、excel、pdf文件)