在项目下载 execl 表格的功能
实现逻辑:前端请求后端接口,后端返回 execl 文件流,前端对文件流进行下载操作;前端封装请求一定要设置responseType:‘blob’;
封装请求:
export function getDownloadTable(data){
return {
url:'请求接口',
method:'POST',
responseType:'blob',
params:data
}
}
组件中请求接口:
methods:{
// 点击下载表格事件
downloadTable(){
getDownloadTable(参数).then(res=>{
this.downloadFile(res,'文件名');
console.log(res)
})
}
}
下载表格事件:
methods:{
downloadFile(data,fileName){
let blob = new Blob([data],{type:`application/vnd.ms-excel;charset=utf-8`});
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
windiw.URL.revokeObjectURL(href);
}
}
简单实现原生 js 下载文件流功能