export function xhrToExportFile(url, method = 'GET', fileName = "文件名称", params = {}, fileType = 'xlsx') {
const token = getCookie(`PHPSESSID`) || '';
let xhr = new XMLHttpRequest();
const hasParams = Object.keys(params).length > 0;
if (method === 'GET' && hasParams) {
const keys = Object.keys(params);
keys.forEach((item, index) => {
url += `${index === 0 ? '?' : '&'}${item}=${params[item]}`
})
}
xhr.open(method, `${url}`, true);
xhr.setRequestHeader("phpsessid", token);
xhr.setRequestHeader('content-type', 'application/json; charset=UTF-8');
xhr.responseType = "blob";
xhr.onload = function(e) {
if (this.status == 200) {
let blob = this.response;
let reader = new FileReader();
reader.readAsDataURL(blob)
reader.onload = function(e) {
let a = document.createElement("a");
a.download = `${fileName}.${fileType}`;
a.href = e.target.result;
// 修复firefox中无法触发click
document.getElementsByTagName('body')[0].append(a);
a.click();
a.remove();
};
} else {
xhr.send();
}
};
if (hasParams || method === 'POST') {
xhr.send(JSON.stringify(params));
} else {
xhr.send();
}
}
import { json2Form,xhrToExportFile } from '@/tools/util';
try {
xhrToExportFile(exportSpecial, 'POST', '专场信息表', this.ad_form);
} catch (e) {
this.$message.error(`导出错误:${e}`)
}
封装 vue 导出 xlsx
最新推荐文章于 2024-02-19 10:56:33 发布
这段代码展示了如何使用xhr和相关工具函数实现从指定URL以POST方式导出文件,参数包括URL、请求方法、文件名、参数对象和文件类型。在响应加载后,将转换为Blob并创建一个隐藏的下载链接,触发下载。如果请求失败,会显示错误消息。
摘要由CSDN通过智能技术生成