axios 下载流文件
后端接口返回一个流文件,下载方法async downLoad(){let url= '/downloadTemplate.do';this.downloadLoading = true;axios.get(url,{baseURL: `/web/api`,responseType:'blob',headers:{Authorization :'Bearer ' + sessionStorage.g
·
后端接口返回一个流文件,下载方法
async downLoad(){
let url= '/downloadTemplate.do';
this.downloadLoading = true;
axios.get(url,{
baseURL: `/web/api`,
responseType:'blob', //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置
headers:{Authorization :'Bearer ' + sessionStorage.getItem('access_token')}
}).then(res => {
this.downloadLoading = false
if (!res) {
this.$message.error("下载模板文件失败");
return false;
}
const blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob);
let contentDisposition = res.headers['content-disposition']; //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
let result = patt.exec(contentDisposition);
let filename = decodeURI(result[1]);
downloadElement.style.display = 'none';
downloadElement.href = href;
downloadElement.download = filename ; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
},
更多推荐
已为社区贡献3条内容
所有评论(0)