1 // 导出
2 exportFn(interfaceRequest ,params ){
3 let token = Cookie.get("admin_token");
4 axios({
5 url:interfaceRequest,
6 method: "get",
7 params:params,
8 headers: {"Authorization": `Bearer `+token},
9 responseType:'blob'
10 }).then(res=>{
11 var blob = res.data;
12 // FileReader主要用于将文件内容读入内存
13 var reader = new FileReader();
14 reader.readAsDataURL(blob);
15 // onload当读取操作成功完成时调用
16 reader.onload = e=> {
17 var a = document.createElement('a');
18 // 获取文件名fileName
19 var fileName = res.headers["content-disposition"].split("=");
20 fileName = fileName[fileName.length - 1];
21 fileName = fileName.replace(/utf-8''/g, "");
22 a.download = decodeURI(fileName);
23 a.href = e.target.result.toString();
24 this.$message.success(this.downFileTxt);
25 document.body.appendChild(a);
26 a.click();
27 document.body.removeChild(a);
28 }
29 }).catch(error=>{
//想要得到后端抛出的错误信息,需要这里特殊处理,因为请求时候设置的responseType为blob,
// 而后端返回的类型是json,需要重新解析
30 if (error.response.data.type === 'application/json') {
31 let reader = new FileReader()
32 reader.readAsText(error.response.data)
33 reader.onload = e => {
34 const { message } = JSON.parse(reader.result.toString());
35 this.$message.error(message)
36 }
37 }
38 })
39 }