工作中的问题,以及解决方案

1、下载流文件的方法(后台传递给前台是一个流文件的url地址):

<a href="流文件的url地址" download="可以是文件名字,也可以是空字符串"></a>

需要注意的:流的文件地址需要是域名的url地址,不能是ip地址的url地址,如果是ip地址的url,那么会直接打开文件,而不会下载文件;download也是必须的,值可以为空,也可以是文件名字,如果为空,默认是下载的文件名

2、针对后台get请求,下载二进制的流文件(后台传递给前台一大串的文件流)

/* 文件导出 */
fileExport () {
  let productName = this.productName
  let productStatus = this.productStatus
  let beginDate = this.beginDate
  let endDate = this.endDate
  let currentPage = this.currentPage
  let perPage = this.perPage
  var params = this.$qs.stringify({
    page: currentPage,
    rows: perPage,
    borrowTitle: productName,
    repaymentQueueStatus: productStatus,
    beginDate: beginDate,
    endDate: endDate
  })
  const url = '/jjsfont/repayment/paymentListToExcel.do?' + params
  this.downloadFile(url)
},
downloadFile (url) {
  try {
    var elemIF = document.createElement('iframe')
    elemIF.src = url
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  } catch (e) {

    }
  }
利用iframe下载二进制流文件
3、针对后端的post请求 利用原生的XMLHttpRequest方法实现

具体实现

function request () {
    const req = new XMLHttpRequest();
    req.open('POST', '<接口地址>', true);
    req.responseType = 'blob';
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      const data = req.response;
      const a = document.createElement('a');
      const blob = new Blob([data]);
      const blobUrl = window.URL.createObjectURL(blob);
      download(blobUrl) ;
    };
    req.send('<请求参数:json字符串>');
  };

function download(blobUrl) {
  const a = document.createElement('a');
  a.style.display = 'none';
  a.download = '<文件名>';
  a.href = blobUrl;
  a.click();
  document.body.removeChild(a);
}

request();

针对后端的post请求 利用原生的fetch方法实现

具体实现

function request() {
  fetch('<接口地址>', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: '<请求参数:json字符串>',
  })
    .then(res => res.blob())
    .then(data => {
      let blobUrl = window.URL.createObjectURL(data);
      download(blobUrl);
    });
}

function download(blobUrl) {
  const a = document.createElement('a');
  a.style.display = 'none';
  a.download = '<文件名>';
  a.href = blobUrl;
  a.click();
  document.body.removeChild(a);
}

request();

4、rsa加密(非对称加密)
 
首先引入node-rsa   import NodeRSA from 'node-rsa'
原理:利用后台传递过来的公钥加密,传递给后台后,后台利用私钥解密,反之亦然
 
RSA_PUBLIC_KEY是后台传递给前台的公钥,message是要加密的密码或者文本
在node-rsa模块中加解密默认使用 pkcs1_oaep ,而在js中加密解密默认使用的是 pkcs1,所以需要设置
步骤:1、使用后台传递过来的公钥生成锁钥
2、设置加密使用的编码格式
3、使用生成后的锁钥,加密文本或密码
4、返回加密后的数据
 
4、postMessage的跨域页面数据传输
 
说明:1.html是处于一个域名下,和2.html所处的域名完全是两个不同的系统,1.html用iframe加载2.html时,给2.html传递了数据,
 
然后2.html拿到数据以后进行对自身页面处理或者只是单单对拿过来的数据进行处理就可以了
需要注意的是:用iframe拿人的数据时,需要设置对方的地址,即截图中的targetOrigin

 
原文地址:https://www.cnblogs.com/zhangycun/p/10138621.html