post方法导出后台返回的单个二进制流文件(get方法,post都适用)
/* 文件下载方法
* @param {String} blobUrl 文件地址,可在url后面添加参数
* @param {String} filename 不支持a标签download的,需要在服务器端设置文件名
* @return {Boolean}
*/
export function downloadFile (data, filename = '') {
const url = window.URL.createObjectURL(
new Blob([data],
{ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
)
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', `${filename}` || 'template.xls');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
post方法导出多个二进制流文件
/**
* @description: 通过Blob 下载文件
* @param {*} Response post 请求的响应体
* @param {string} fileName 自定义文件名
* @return {*}
*/
export function downloadFileFromBlob (Response) {
let type = Response?.headers?.['content-type']; // 获取响应类型
let nameStr = Response?.headers?.['content-disposition']; // 获取文件名字符串
let downloadName = nameStr.split('filename=')[1];
let blob = new Blob([Response?.data], { type });
let href = URL.createObjectURL(blob);
// decodeURI方法用于转译后台返回的文件名
download(href, decodeURI(downloadName).replace(/\"/g, ''));
window.URL.revokeObjectURL(href);
}
const res = await $ajax({
url: `url`,
method: 'POST',
data: params,
responseType: 'blob'
});
download(res, `template.xlsx`)