角度2触发excel下载

时间:2017-03-31 22:03:37

标签: rest angular http typescript download

当后端已经在响应中提供下载时,如何在角度2中触发下载?

我的后端提供了这样的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
    });

但现在我不知道如何使用响应触发下载(不知道我应该如何映射它或者是什么)

1 个答案:

答案 0 :(得分:0)

一个非常简单的解决方案:如果端点已经触发下载,则只需构建端点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;
相关问题