vue前端下载文件
材料
- vue2
- axios
- elementUI
描述
前端表格下载pdf文件
downloadReport(params){ //参数是表格行数据
var fileName = this.getFileName(params,"步态分析") //从表格行数据提取文件名方法
this.fullscreenLoading = true; //elementUI的loading组件
setTimeout(()=>{
this.fullscreenLoading = false //超时关闭loading
},10000)
downloadFootPdfApi(params.id).then(res=>{ //向后端请求
this.download(res,fileName) //成功拿到response流
}).catch(()=>{
this.fullscreenLoading = false //失败关闭loading
})
},
download(res, fileName) {
if(!res) {
return ;
}
const blob = new Blob([res], {type: 'application/pdf'}); //新建一个Blob类型pdf。各种文件类型参考https://www.w3school.com.cn/media/media_mimeref.asp
let url = window.URL.createObjectURL(blob); //一个DOMString包含了一个对象URL,该URL可用于指定源 object的内容。参考https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
let link = document.createElement('a'); //创建一个a标签
link.style.display = 'none';
link.href = url; //赋予href属性 为url
link.download = decodeURIComponent(fileName);
document.body.appendChild(link);
link.click(); //模拟点击a标签
document.body.removeChild(link);
window.URL.revokeObjectURL(url); // 释放掉blob对象
this.fullscreenLoading = false;
},
//下载PDF接口
export function downloadGaitApi(id){
return request({
url: '/scanning/downloadFile/downloadGaitPdf/' + id,
method: 'get',
responseType: 'blob'
})
}