关于post方式JSON字符串传参导出文件的一种方法实现

在公司因为之前接触的东西,一般`get`采用的是`a`标签,然后`post`采用的是`form`表单,但是今天突然遇到了`post`请求,`json`字符串传参,于是发现了这种方式。
axios.post('export',data,{responseType:'blob'}) // 响应类型为blob字节流
  .then(res => {
    let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }); // 这里是xls
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, res.fileName)
    } else {
      let downloadElement = document.createElement('a');
      let href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = res.fileName; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
   }
  })
posted @ 2022-06-09 17:09  chichisky  阅读(311)  评论(0)    收藏  举报