一、get请求导出文件
1、window.open(url)
会自动打开一个标签页,下载完后会自动关闭这个标签页。
2、window.location(url) 或 location.href = url
在当前标签页下载。
3、< a href=“url” download=“filename”>点击链接下载< /a>
在当前标签页下载。
总结
优点:代码简单。
缺点:当导出失败时,返回的错误信息会覆盖原来的页面,错误信息可读性差。
二、post请求导出文件
1、思路
通过判断返回值的header.‘content-type’ 是否是 application/octet-stream,来确定文件导出是否成功!
content-type:
(1).application/octet-stream: 返回值类型为二进制流,即导出成功;
(2).application/json;charset=utf-8:返回值类型为json格式,即导出失败信息。由于我们请求的时候设置了responseType=‘blob’,所以返回值会被转换成二进制流。
实现
(1).接口处理类型(blob):
export const postExport = (params = {}) => {
return http.post(`${baseURL}/api/demand/purchasingPlanExport`, (params), {responseType: 'blob'}).then(res => res.data)
}
(2).业务实现
// 接口请求函数
postExportApi() {
// promise处理异步
return new Promise((resolve) => {
// postExport(),接口地址
postExport().then((res) => {
// 导出失败,返回错误信息
if (res.type !== 'application/octet-stream') {
// 将返回的blob格式的返回值,转成对象,取出Response数据
new Response(res.data).text().then((res) => {
console.log(res);
})
} else {
// downloadName 定义文件夹名称
let downloadName = `采购计划.xlsx`;
// 使用blob函数下载文件
let blob = new Blob([res], { type: `application/vnd.ms-excel` });
let downloadElement = document.createElement("a");
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = downloadName;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
this.$refs["modal"].show = false;
}
});
});
},
总结
优点:当导出失败时,可以以一种更优雅的方式展示错误提示信息。
缺点:代码复杂。