导出/下载----->get/post请求
utils
export const appendObjectToUrl = (url, obj) => {
const query = Object.keys(obj)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
.join("&");
const separator = url.includes("?") ? "&" : "?";
const modifiedUrl = `${url}${separator}${query}`;
return modifiedUrl;
};
调用
const downloadUrl = `路径`;
const query = {
参数
};
const url = appendObjectToUrl(downloadUrl, query);
window.open(url);
api封装
export const exportNoteList = (data) =>
http({
url: 请求路径,
headers: {
httpWhite: true,
},
responseType: "blob",
rawresp: true,
method: "post",
data,
});
调用
handleExport() {
this.$message.error("条件不能为空");
const query = {
参数
};
exportNoteList(query)
.then((res) => {
if (res.status == 200) {
downloadDataTemplate(res);
}
})
.catch((error) => {
console.error("导出失败:", error);
});
},
utils
downloadDataTemplate(res) {
let fileName = "导出数据.xlsx";
const contentDisposition = res.headers["content-disposition"];
if (contentDisposition && contentDisposition.includes("filename=")) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(contentDisposition);
if (matches != null && matches[1]) {
fileName = decodeURIComponent(matches[1].replace(/['"]/g, ""));
}
}
const blob = new Blob([res.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
});
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
},