如果你使用常规的 new Blob 方法,出现生成文件很慢,造成请求超时的情况,就只能改用传统的form 提交表单的方法了
// 把后端返回的文件流变成一个 Blob 对象
const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
// 设置文件名
const fileName = name ? name + '.xls' : '导出的表格文件.xls'
// 对于<a>标签,只有 Firefox 和 Chrome(内核)支持 download 属性
if ('download' in document.createElement('a')) {
// 创建 a 标签
const link = document.createElement('a')
// 设置 a 的链接地址,用 createObjectURL 方法创建一个url下载地址
link.href = window.URL.createObjectURL(blob)
// 设置下载地址的文件名
link.download = fileName
// 让浏览器自动点击 a 的超链接
link.click()
// 释放内存
window.URL.revokeObjectURL(blob)
} else {
// IE 浏览器兼容方法
window.navigator.msSaveBlob(blob, fileName)
}
这个方法会比较慢,造成浏览器响应超时,从而丢失数据,所以可以改用下边的 form 表单提交方法
let $iframe = document.createElement('iframe');
let $form = document.createElement('form');
let urlTwo = Setting.apiBaseURL + url
$iframe.setAttribute('id', 'down-file-iframe');
$form.setAttribute('target', '_self');
$form.setAttribute('method', 'post');
$form.setAttribute('enctype', 'multipart/form-data');
$form.setAttribute('accept-charset', 'UTF-8')
$form.setAttribute('action', urlTwo);
for (let key in params) {
let dom = document.createElement('input');
dom.setAttribute('type', 'hidden');
dom.setAttribute('name', key);
dom.setAttribute('value', params[key]);
$form.appendChild(dom);
}
$iframe.appendChild($form);
document.body.appendChild($iframe);
$form.submit();
$iframe.remove();
使用这个方法就不会造成响应超时了