【_ 記 】vue项目 axios发送post请求下载文件,解决下载格式问题

页面

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

axios请求

注意:
responseType为blob


Blob(blobParts[, options])
返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。

Blob 语法:

var aBlob = new Blob( array, options );
在这里插入图片描述
在这里插入图片描述

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

进行请求处理

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); 
          document.body.removeChild(elink);
        });
      },

补充:
'格式
const blob = new Blob([response.data],{type: ‘application/vnd.ms-excel’})
{type: ‘text/plain;charset=UTF-8’}

发布了116 篇原创文章 · 获赞 116 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/o_o814222198/article/details/103766075