参考代码
//url请求地址,datas传给后台的参数,fileName文件名,format文件类型后缀名如.xls
downLoadFile(url,datas,fileName,format){
this.http.post(url, datas, { responseType: 'blob' }).subscribe((result:any)=>{
const link = document.createElement('a');
const blob = new Blob([result], { type: 'application/zip' });
link.setAttribute('href', window.URL.createObjectURL(blob));
link.setAttribute('download', fileName + format);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
};
改造代码:
// 处理下载
hangleDownloadFile(val){
let {attachId , attachName , } = val
let fileName = attachName //赋值文件名
let fileType = fileName.substr(fileName.lastIndexOf(".")+1); //获取文件后缀名
download(attachId).then((result)=>{
const link = document.createElement('a'); //创建a标签
const blob = new Blob([result], { type: `application/${fileType}` });
link.setAttribute('href', window.URL.createObjectURL(blob));
link.setAttribute('download', fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
},
}
注意:接受这种类型的时候要把ajax接受的格式改为blob
// 下载
export function download(id) {
return axios({
url: `/annex/download/${id}`,
method: 'get',
responseType: 'blob' // 注意点
})
}