之前下载文件都是使用 windows.location.href
,点击直接下载后台已经生成好的文件。
最近接触vue项目,学习了一种后台传输文件流,前台使用blob
方法接收文件流,记录如下。
导出方法:
uploadFile(name, type, title){
downloadExcel({name, type}).then(rst => {
this.downloadFile(rst,title);
})
},
downloadFile(data,title) {
// 文件导出
if (!data) {
return
}
let url = window.URL.createObjectURL(data.data);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', title+'.xls');
document.body.appendChild(link);
link.click()
}
接口写法:
// 导出投票结果excel
export const downloadExcel = (params) => {
let {name, type} = params;
return axios.request({
url: `${**}/**/download/${name}/${type}`,
method: 'get',
responseType:'blob', // 注意这里!!!
});
};