角度2触发器excel下载
问题描述:
当后端已经在响应中提供下载时,我如何在角度2中触发下载?角度2触发器excel下载
我的后端提供一个这样的API端点:
Workbook userExcelReport = excelReportGenerator.createUserExcelReport(userSurveys);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=\"" + userFileName + ".xlsx\"");
try {
userExcelReport.write(response.getOutputStream());
userExcelReport.close();
response.flushBuffer();
return new ResponseEntity(HttpStatus.OK);
} catch (IOException e) {
logger.error("The excel workbook could not write to the outputStream ", e);
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
该方法被证明可行,(如进入后端(无前端)触发下载正确的),但现在我想打一个角第2页触发下载
我有几分页面准备好,我有这个在服务:
return this._http.get(this.url, {
search: params
});
,但现在我不知道如何触发向下与响应负载(不知道我应该如何映射它还是什么)
答
一个非常简单的解决方案:如果端点已经触发下载只是建立端点url(其查询参数)
this.url += '/api/survey/report/';
this.url += this.adminForm.get('fileType').value;
if (this.adminForm.get('evaluated').value !== null || this.adminForm.get('startDate').value !== null
|| this.adminForm.get('endDate').value !== null) {
this.url += '?';
if (this.adminForm.get('evaluated').value !== null) {
this.url += '&name=';
this.url += this.adminForm.get('evaluated').value;
}
if (this.adminForm.get('startDate').value !== null && this.adminForm.get('startDate').value !== '') {
this.url += '&startdate=';
this.url += this.adminForm.get('startDate').value;
}
if (this.adminForm.get('endDate').value !== null && this.adminForm.get('endDate').value !== '') {
this.url += '&enddate=';
this.url += this.adminForm.get('endDate').value;
}
}
和那么只需重定向
window.location.href = this.url;
this.url = environment.apiURL;
您可以直接链接到您的excel资源URL。或者使用window.location使浏览器访问该网址并下载文件。无需使用AJAX请求。 –
可能重复的[Javascript:创建并保存文件](http://stackoverflow.com/questions/13405129/javascript-create-and-save-file) – toskv
@toskv但这是关于创建一个文件,这个问题是关于触发后端响应实体的下载.-。 –