1.post请求导出文件
exportFile = function(params, url) {
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.responseType = "blob"; // 返回类型blob
xhr.send(JSON.stringify(params)); // 发送ajax请求
xhr.onreadystatechange = function () {
// 监听属性xhr.readyState每次变化时会触发
if (xhr.readyState === XMLHttpRequest.DONE) {
// 响应已返回
var code = decodeURI(xhr.getResponseHeader("code"));
console.log(code);
if (code.toString() === "0") {
$.messager.alert('提示', "操作成功!");
// 截取文件名,这里是后端返回了文件名+后缀,如果没有可以自己拼接
var fileName = decodeURI(xhr.getResponseHeader("content-disposition").split(";")[1].split("=")[1]);
console.log(fileName);
// 将`blob`对象转化成一个可访问的`url`
let dataUrl = window.URL.createObjectURL(new Blob([xhr.response]));
let link = document.createElement("a");
link.style.display = "none";
link.href = dataUrl;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
var msg = decodeURI(xhr.getResponseHeader("msg"));
$.messager.alert('提示', msg);
}
}
}
}