話不多說,上代碼:
try {
let reader = new FileReader();
let blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' });
reader.readAsArrayBuffer(blob);
reader.onload = function() {
let data = new Blob([this.result]);
// 判斷是否為文件流數據
if (data.size === 0) this.$message({ message: '生成文件失敗', type: 'error' });
};
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob); // 創建下載的鏈接
let head = res.headers['content-disposition'];
if (!head) {
this.$message({ message: '導出失敗', type: 'error' });
return;
}
downloadElement.href = href;
head = decodeURI(head.split(';')[1].split('=')[1]); // url轉碼中文
downloadElement.download = head; // 下載后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 點擊下載
document.body.removeChild(downloadElement); // 下載完成移除元素
window.URL.revokeObjectURL(href); // 釋放掉blob對象
} catch (e) {
let head = res.headers['content-disposition'];
head = decodeURI(head.split(';')[1].split('=')[1]); // url轉碼中文
if ('msSaveOrOpenBlob' in navigator) {
window.navigator.msSaveOrOpenBlob(new Blob([res.data]), head);
} else {
const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' }));
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', head);
document.body.appendChild(link);
link.click();
}
}
