Get方式导出Excel
import { baseUrl } from "@/config/env";
import { G_Page_Token } from "./auth";
export function outExcelSingleByGet(url, params) {
params.Authorization = "Bearer " + G_Page_Token();
let tempURL = process.env.NODE_ENV === "development" ? '开发地址' : baseUrl + '/fatsapi/invoice/'+url;
let url= urlAddParams(tempURL, params);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", "");
document.body.appendChild(link);
link.click();
hideLoading();
link.remove();
}
// 拼接参数
function urlAddParams(url, params) {
let tmp = "";
if (params) {
for (let i in params) {
tmp += i + "=" + params[i] + "&";
}
tmp = url + "?" + tmp.substr(0, tmp.length - 1);
} else {
tmp = url;
}
return tmp;
}
众所周知,导出excel等大多直接通过window.open(get请求地址)方式下载导出,但这种方式会闪下页面才执行下载,不够友好,故采用了以上方式。正在窃喜时~~~ ^.^
测试发现IE不好用,原来 Eee~~~ IE浏览器字符串长度超过限制,被截取拉~~,故post导出方式在几经磨难之后,诞生了~
直接上Code:
import { exportRZQD } from '@/api/api';
import qs from 'qs';
export function outExcelSingleByPost(params) {
let reqData = qs.stringify(params);//qs转formdata形式
const headers = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',// 采用formdata方式传参
'token': 'Bearer '+ G_Page_Token()
},
responseType: 'blob' //必传
}
exportRZQD(reqData,headers).then(res => {
const content = res.data;
let len = res.headers['content-disposition'].length;
const blob = new Blob([content]);
const fileName = decodeURI(res.headers['content-disposition'].substring(20, len));
if ('msSaveOrOpenBlob' in navigator) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
return;
}
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = window.URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
window.URL.revokeObjectURL(elink.href);// 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
window.navigator.msSaveBlob(blob, fileName)
}
}, error => {
hideLoading();
});
}
这次开发,因为改造别人代码,故温习了一下请求封装
import axios from 'axios';
export function post(url,params,config) {
return new Promise((resolve, reject) => {
axios
.post(url, params, config)
.then(
res => {
resolve(res)
},
err => {
reject('网络连接失败,请稍后重试')
}
)
.catch(err => {
reject('网络连接失败,请稍后重试')
})
})
}
注:在开发过程中才知道config就是请求头的数据