2017-03-31 71 views
1

當後端已經在響應中提供下載時,我如何在角度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 
    }); 

,但現在我不知道如何觸發向下與響應負載(不知道我應該如何映射它還是什麼)

+0

您可以直接鏈接到您的excel資源URL。或者使用window.location使瀏覽器訪問該網址並下載文件。無需使用AJAX請求。 –

+0

可能重複的[Javascript:創建並保存文件](http://stackoverflow.com/questions/13405129/javascript-create-and-save-file) – toskv

+0

@toskv但這是關於創建一個文件,這個問題是關於觸發後端響應實體的下載.-。 –

回答

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;