vue+post请求导出excel

99 阅读1分钟

最近有些奇奇怪怪的需求。比如后端没读法取服务器权限因此没法做到文件导出或者利用oss导出(公司没钱)。导致导出的时传文件流给前端让前端获取。最奇怪是居然不用get用post说是文件过大怕前端接收不全。。 这什么扯淡玩意。。get只是浏览器对url长度做了限制罢了。

算了遇到这么弱的后端你只能配合没法子。 唯一用blob的好处就是防止盗链和可以加密。自我安慰吧。
因此产生了如何在封装了http请求里面利用axios获取文件流导出excel?

下面上代码

重点:responseType: 'blob'

const axiosReq = (url, params) => {  
  axios  
    .post(url, params, {  
      responseType: "blob",  
      headers: { "Content-Type": "application/json" }  
    })  
    .then(res => {  
      console.log(res, "axios");  
      const blob = new Blob([res.data], {  
        type: "application/zip;"  
      });  
      const downloadElement = document.createElement("a");  
      const href = window.URL.createObjectURL(blob);  
      const filename = res.headers["content-disposition"]  
        .split(";")[1]  
        .split("=")[1]; //filename;  
      downloadElement.href = href;  
      downloadElement.download = filename; //命名下载名称  
      downloadElement.click();  
      window.URL.revokeObjectURL(href); //下载完成进行释放  
    })  
    .catch(e => {  
      ElMessage.error(e.message);  
    });  
};