1.定义一个公共的文件流请求方法
/**
* 文件流返回
* @param url 接口地址
*/
export const exportBlob = (url) => {
return request({
url: url,
method: 'get',
responseType: 'blob'
})
}
2.封装一个excel下载的方法
/**
* 下载excel
* @param {blob} fileArrayBuffer 文件流
* @param {String} filename 文件名称
*/
export const downloadXls = (fileArrayBuffer, filename) => {
let data = new Blob([fileArrayBuffer], {type: 'application/vnd.ms-excel,charset=utf-8'});
if (typeof window.chrome !== 'undefined') {
// Chrome
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = filename;
link.click();
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE
var blob = new Blob([data], {type: 'application/force-download'});
window.navigator.msSaveBlob(blob, filename);
} else {
// Firefox
var file = new File([data], filename, {type: 'application/force-download'});
window.open(URL.createObjectURL(file));
}
}
/**
* 当前时间戳
*/
export function dateNow() {
return dateFormat(new Date(), "yyyyMMddhhmmss");
}
3.具体调用
import { exportBlob } from "@/api/common";//引入文件流请求方法
import { getToken } from '@/util/auth';//一般需要鉴权
import {downloadXls} from "@/util/util";//引入excel下载方法
import {dateNow} from "@/util/date";//导出文件名加上时间戳
handleExport() {
this.$confirm("是否导出列表?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(() => {
NProgress.start();
exportBlob(`/api/export-visitor?${tokenHeader}=${getToken()}`).then(res => {
downloadXls(res.data, `列表${dateNow()}.xlsx`);
NProgress.done();
})
});
},
这样就可以顺利导出啦