post请求将数据传给后端,后端将文件以二进制的形式发给前端,前端进行接收并下载

post请求将数据传给后端,后端将文件以二进制的形式发给前端,前端进行接收并下载(不支持IE8、IE9)

  1. 利用原生的XMLHttpRequest方法实现

在这里插入图片描述
post请求将数据传给后端,后端将文件以二进制的形式发给前端,前端进行接收并下载_第1张图片

    ![exportList(fzjglx) {
      //todo zhy 添加一个【导出】按钮
        const {
     dataSourceFourth} = this.state;
        if (!dataSourceFourth.length) {
     
            Message.modalError('表格没有数据,请添加数据后再进行导出!', '温馨提示');
            return
        }
        const req = new XMLHttpRequest();
        r![在这里插入图片描述](https://img-blog.csdnimg.cn/20200227002356683.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTU0OTQ4MQ==,size_16,color_FFFFFF,t_70)eq.open('POST', `/hgzx-web/api/qysdshznszfjgxxba/excelExport/${
       fzjglx}`, 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);
            a.style.display = 'none';
            a.download = 'HZNSQYQKDJ_XYJJGXX_DOWNLOAD.xls';
            a.href = blobUrl;
            a.click();
            document.body.removeChild(a);
        };
        req.send(JSON.stringify({
     exportList: dataSourceFourth}));
    },

post请求将数据传给后端,后端将文件以二进制的形式发给前端,前端进行接收并下载_第2张图片

![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()
`](https://img-blog.csdnimg.cn/20200227001856109.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTU0OTQ4MQ==,size_16,color_FFFFFF,t_70)``

你可能感兴趣的:(拓展)