借鑒文章:https://blog.csdn.net/developer_qi/article/details/87803950
一、 處理文件流
① 請求接口時,聲明responseType: 'blob', 告訴后台需要返回的的報文是文件
export function writeWithHead(params) {
return request({
url: window.CONFIG.restIp + '/workOrderExcelOutDto/writeWithHead',
method: 'post',
data: params,
responseType: 'blob', // 請求的時候必須添加
timeout: 200000
})
}
② 處理后台返回的流數據
writeWithHead(params).then(res => {
if (res.status === 200) {
this.$message({
type: "success",
message: '導出成功'
})
const blob = new Blob([res.data]);
const fileName = '導出文件.xlsx';//下載文件名稱
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 釋放URL 對象
document.body.removeChild(elink);
} else {
this.$message({
type: "error",
message: '導出失敗'
});
}
});
二、 base64碼 (原理一樣,多一步操作,需要將base64碼轉換成文件流后在操縱)
writeWithHead(params).then(res => { if (res.status === 200) { this.$message({ type: "success", message: '導出成功' }) this.downloadFileByBase64(res.data,'導出列表') } else { this.$message({ type: "error", message: '導出失敗' }); }}); dataURLtoBlob (dataurl, filename) { let arr = dataurl.split(","); let mime = arr[0].match(/:(.*?);/)[1]; let bstr = atob(arr[1]); let n = bstr.length; let u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }, downloadFile (url, name = "導出列表") { var a = document.createElement("a"); a.setAttribute("href", url); a.setAttribute("download", name); a.setAttribute("target", "_blank"); let clickEvent = document.createEvent("MouseEvents"); clickEvent.initEvent("click", true, true); a.dispatchEvent(clickEvent); }, downloadFileByBase64 (base64, name) { let myBlob = this.dataURLtoBlob(base64); let myUrl = URL.createObjectURL(myBlob); this.downloadFile(myUrl, name); },
有不足之處,還望大佬多指教
