Angular / Vue HTTP POST下载流文件
HTTP POST 请求流文件转成excel
Angular / Vue HTTP POST下载流文件HTTP POST 请求流文件转成excel在使用Angular开发项目时,通常会有下载文件的功能项。一般是后台返回下载地址,通过
标题或者使用 window 打开下载地址新窗口,浏览器则会识别出流文件进行文件下载。但是,有时候进行http异步请求,后台返回的并不是下载地址,而是直接返回一个文件流,这时如何使用http请求回来的文件流转换成文件下载?其实并非Angular框架存地这样的情况,其他PWA如Vue,React甚至Jquery都通过http xhr进行请求而获取的流文件,浏览器也并不会自动识别并自动下载。那当然,肯定有解决方案。方案思路:http请求使用blob的返回类型,获取文件流后,对数据进行Blob,再提交给浏览器进行识下面是代码示例下面是代码示例
/**
* 导出excel
*/
exportExcel(){
const params = {}; // body的参数
const queryParams = undefined; // url query的参数
this.http.post(this.exportUrl, params, queryParams, {
responseType: "blob",
headers: new HttpHeaders().append("Content-Type", "application/json")
}).subscribe(resp=>{
// resp: 文件流
this.downloadFile(resp);
})
}

/**
* 创建blob对象,并利用浏览器打开url进行下载
* @param data 文件流数据
*/
downloadFile(data) {
// 下载类型 xls
const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
// 下载类型:csv
const contentType2 = 'text/csv';
const blob = new Blob([data], { type: contentType });
const url = window.URL.createObjectURL(blob);
// 打开新窗口方式进行下载
// window.open(url);

// 以动态创建a标签进行下载
const a = document.createElement('a');
const fileName = this.datePipe.transform(new Date(), 'yyyyMMdd');
a.href = url;
// a.download = fileName;
a.download = fileName + '.xlsx';
a.click();
window.URL.revokeObjectURL(url);
}

/**
* 导出excel
*/
exportExcel(){
const params = {}; // body的参数
const queryParams = undefined; // url query的参数
this.http.post(this.exportUrl, params, queryParams, {
responseType: "blob",
headers: new HttpHeaders().append("Content-Type", "application/json")
}).subscribe(resp=>{
// resp: 文件流
this.downloadFile(resp);
})
}

/**
* 创建blob对象,并利用浏览器打开url进行下载
* @param data 文件流数据
*/
downloadFile(data) {
// 下载类型 xls
const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
// 下载类型:csv
const contentType2 = 'text/csv';
const blob = new Blob([data], { type: contentType });
const url = window.URL.createObjectURL(blob);
// 打开新窗口方式进行下载
// window.open(url);

// 以动态创建a标签进行下载
const a = document.createElement('a');
const fileName = this.datePipe.transform(new Date(), 'yyyyMMdd');
a.href = url;
// a.download = fileName;
a.download = fileName + '.xlsx';
a.click();
window.URL.revokeObjectURL(url);
}
总结总结