vue项目中,后端返回文件流,axios发送post请求下载文件

1.html

 <el-button type="primary" @click.native="handleExport">下载</el-button>

2.修改axios请求的responseType为blob,以post请求为例

export function export(params) {
  return axios({
    headers: {
      'Content-Type':'application/json'
    },
    responseType: 'blob', //一定要写
    method: 'post',
    url:'/export',
    data:{
      "head": {},
      "body": {
        "data":params
      }
    }
  })
}

3.进行请求处理

handleExport() {
        const params = {};
        export(params).then(res => {
          console.log(res.data)
          const blob = new Blob([res.data]);//处理文档流
          const fileName = 'excel.xlsx';
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        });
      },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容