美文网首页
js vue 下载docx文件/ pdf文件/ 打印pdf /

js vue 下载docx文件/ pdf文件/ 打印pdf /

作者: Peter_2B | 来源:发表于2021-08-06 18:23 被阅读0次
image.png
下载docx or zip
fetch('http://172.16.133.206:3000/api/crisps-elec-mid/yk/elec/mid/template/download_template.do?templateIdList=1379369742456244186', {
        headers: {                                    // 用于验签,验签功能取决于公司是否有验签需求,一般只验证token;
            nonce: "57574625-6dad-4eda-8073-5697160c356c",
            sign: "4D511B5974D175C1754BFCCABC2803B8",
            sysCode: "crisps-contract",
            time: "1628158964707",
            userId: "767584325286131174",
            "X-Auth-Token": "1379368986541972974",    // 只验证token,只需要在请求拦截器统一设置
            "X-Req-UserId": "1379368986541972974"
        }
      }).then(r=>r.blob()).then(blob=>{  // r就是从后端获取到的文件流

          const href = URL.createObjectURL(blob);
          Object.assign(document.createElement('a'), {
            href,
            download: tempArr.length === 1 ? '合同模板.docx' : '合同模板.zip',
          }).click();
          URL.revokeObjectURL(href);
        }
      )
打印
print_contract({ fileId: this.id }).then((data) => {    // 后端返回得是base64位的图片数组
          const iframe = document.createElement('iframe');

          iframe.onload = function () {
            iframe.contentWindow.document.write(
              data
                .map((item) => {
                  return `<img src="${item}" />`;
                })
                .join(''),
            );
            setTimeout(() => {
              iframe.contentWindow.print();    // 直接打印会空白,利用一点间隙时间
            }, 100);
          };
          iframe.hidden = true;
          document.body.appendChild(iframe);
        }).catch((err) => { });
下载pdf
    downLoad(id, name) {
      this.loading = true;
      download_contract({ fileId: id })   // 传入当前id 以获取pdf下载url
        .then((data) => {  // data = 'http://.....' 下载url
          fetch(data)  
            .then((res) => res.blob())
            .then((result) => {
              let blobUrl = window.URL.createObjectURL(result);
              const a = document.createElement('a');
              a.download = name + '.pdf';
              a.href = blobUrl;
              a.click();
              URL.revokeObjectURL(blobUrl);
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        })
        .catch((err) => {
          this.loading = false;
        });
    },

下载excel

  • downloadFile.js
import axios from 'axios';
import gatewaySign from '@fe/gateway-sign';
import vue from 'vue';

import CONFIG from '@/config';

export async function exportFun(url, params, fn) {
  //签名
  const signData = gatewaySign.handleSign({
    sysCode: CONFIG.default.SYS_CODE,
    secret: CONFIG.default.SECRET,
    token: JSON.parse(localStorage.getItem('token')),
  });

  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      data: params,
      url: '/api/crisps-fund-center-view' + url, //url,
      responseType: 'blob',
      headers: {
        sysCode: CONFIG.default.SYS_CODE,
        // secret: CONFIG.default.SECRET,
        token: JSON.parse(localStorage.getItem('token')),
        'X-Req-UserId': JSON.parse(localStorage.getItem('token')),
        userId: JSON.parse(localStorage.getItem('userId')),
        mchInfo: JSON.parse(localStorage.getItem('mchInfo')),
        // content-type: application/json,
        ...signData,
      },
    }).then((res) => {
      fn && fn();
      let reader = new FileReader();
      reader.readAsText(res.data, 'utf-8');
      reader.onload = (e) => {
        try {
          let result = JSON.parse(e.target.result);
          resolve(result);
        } catch (err) {
          //正常下载
          resolve(res);
        }
      };
    });
  });
}
export async function downloadFile(url, params, fn) {
  const res = await exportFun(url, params, fn);
  console.log(res, '88888');
  if (res.code) {
    vue.prototype.$message.error(res.message);
  } else {
    let blob = new Blob([res.data], {
      type: `application/vnd.ms-excel;charset=utf-8`,
    }); //获取heads中的filename文件名

    let downloadElement = document.createElement('a'); //创建下载的链接
    let href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    document.body.appendChild(downloadElement);
    let contentDisposition = res.headers['content-disposition'];
    if (contentDisposition) downloadElement.download = decodeURI(contentDisposition.split('=')[1]); //导出的文件名
    //return    false
    downloadElement.click(); //下载完成移除元素
    document.body.removeChild(downloadElement); //释放掉blob对象
    window.URL.revokeObjectURL(href);
  }
}

 await downloadFile('/yk/merchant/v1/amount_detail_list.file', params);

相关文章

网友评论

      本文标题:js vue 下载docx文件/ pdf文件/ 打印pdf /

      本文链接:https://www.haomeiwen.com/subject/qbdbvltx.html