先上代碼:
Vue.prototype.download = function(oUrl, filename) {
this.axios
.get(oUrl, { responseType: 'arraybuffer' })
.then((res) => {
console.log(res);
// type 為需要導出的文件類型,此處為xls表格類型
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
// 兼容不同瀏覽器的URL對象
const url = window.URL || window.webkitURL || window.moxURL;
// 創建下載鏈接
const downloadHref = url.createObjectURL(blob);
// 創建a標簽並為其添加屬性
let downloadLink = document.createElement('a');
downloadLink.target = '_blank';
downloadLink.href = downloadHref;
filename = filename ? filename : new Date().getTime();
downloadLink.download = filename + '.xls';
// 觸發點擊事件執行下載
downloadLink.click();
})
.catch((err) => {
console.error(err);
});
// window.open(location.origin + axios.defaults.baseURL + oUrl); //直接跳轉文件地址下載,有些頁面無法正常下載,暫未解決,待排查。
};
請求一定要設置
responseType: 'arraybuffer'
createObjectURL(blob)中的地址一定要是Blob對象:
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
