项目中有个需求请求接口获取下载的excel文件流并实现下载。
angular封装的post请求始终打印不出成功回调里的result, 一直走error。
换了个思路,使用原生的ajax发送请求。
点击下载调用downloadFile方法,用原生的ajax,重点来了,要设置responseType为'blob',
我们的请求需要加Authorization传登录时存的token
downloadFile(fileName) {
const that =this;
const req =new XMLHttpRequest();
req.open('POST', this.archiveNew +'/EC/query/downLoadOrder', true);
req.responseType ='blob';
req.setRequestHeader('Content-Type', 'application/json');
req.setRequestHeader('Authorization', 'Bearer ' +this.jwtToken);
req.onload =function() {
const data = req.response;
//获取到响应通过blob转换后拿到blobUrl,动态创建一个a标签调用click方法,实现下载
const blob =new Blob([data]);
const blobUrl = window.URL.createObjectURL(blob);
that.downloadMethod(blobUrl, fileName);
};
//一定要注意JSON.stringify序列化post传的参数
const data = JSON.stringify({'fileName': fileName});
req.send(data);
}
downloadMethod(blobUrl, fileName) {
// console.log(blobUrl);
const a = document.createElement('a');
a.className ='downloadFileA';
a.style.display ='none';
a.download = fileName;
a.href = blobUrl;
a.click();
$('.downloadFileA').remove();
}