function handelExport(response,type){
let fileName = decodeURI(response['headers']['content-disposition'].split('filename = ')[1]); //不同情況對應取值不同處理可能不同囱挑,以實際情況處理
let blob = new Blob([response.data], {
type: type+';charset=utf-8'
});
let src = window.URL.createObjectURL(blob);
if(src){
let a = document.createElement('a');
a.setAttribute('href', src);
a.setAttribute('download', fileName);
let evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
a.dispatchEvent(evObj);
}
}
type格式可選擇可以參考我另外一篇文章【office文件所對應的的 Content-type類型Content-type類型總結(jié)】(http://www.reibang.com/p/4b09c260f9b2
)
需要注意的點
1:有時候fileName后臺返回或者前端寫死的洲鸠,如果只是單純的文件名不加文件后綴,這個時候在IE瀏覽器下下載的文件可能不能識別刻撒,這個時候可以在fileName上加上后綴(eg:.zip)即可以解決IE下下載文件格式錯誤問題。
2:如果后端返回的是byte流韧献,在請求接口時舌劳,請求頭要加上responseType: 'blob'.
this.$axios.post('/api/xxx', params, {
responseType: 'blob'
}).then((res) => {
if (res.data.size) {
this.handelExport(res,'application/zip');
} else {
this.$message.error(res.data.message || '導出excel失敗,請稍后再試');
}
}).catch((err) => {
this.$message.error(err.message || '導出excel失敗军洼,請稍后再試');
});