//下载数据流文件
export function exportFilePublic(name = "文件名称", url, data = {}, callback) {
const token = localStorage.getItem("token");
let xmlResquest = new XMLHttpRequest();
//proxyData为接口baseUrl
xmlResquest.open("POST", proxyData + url, true);
xmlResquest.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded; charset=utf-8"
);
xmlResquest.responseType = "blob"; // 区分流 ?和字符的区别
xmlResquest.onload = function () {
let content = null;
// 另一只种方法
let reader = new FileReader(); // 挂载
reader.onload = (e) => {
try {
let res = JSON.parse(e.target.result);
message.error(res.message);
if (callback) {
callback();
}
return;
} catch (err) {
content = xmlResquest.response;
let elink = document.createElement("a");
elink.download = name + ".xlsx";
elink.style.display = "none";
let blob = new Blob([content], { type: "text/plain;charset=utf-8" });
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, name + ".xlsx");
} else {
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
}
if (callback) {
callback();
}
}
};
// readAsText?方法是异步的?必须要挂载?实例下的?onload?或?onloadend?的方法处理转化后的结果
reader.readAsText(xmlResquest.response);
};
xmlResquest.send(`${stringify({ ...data, token })}`);
xmlResquest.onerror = () => {
if (callback) {
callback();
}
message.error("下载文件错误!");
};
}
|