我在使用 angular 6 從 rest api 下載文件時遇到問題后端方法 @RequestMapping(value = "/print/{id}") public ResponseEntity<byte[]> generateReport(@PathVariable("id") long id_project){ Map<String, Object> mapper = new HashMap<String, Object>(); byte[] content = exportService.export(mapper, ReportUtils.testReport, ReportUtils.FileFormat.PDF.toString()); return new ResponseEntity<>(content, Utils.getPDFHeaders("Situation_test.pdf"), HttpStatus.OK); }方法 getHeaderpublic static HttpHeaders getPDFHeaders(String fileName) { HttpHeaders head = new HttpHeaders(); head.setContentType(MediaType.parseMediaType("application/pdf")); head.add("content-disposition", "attachment; filename=" + fileName); head.setContentDispositionFormData(fileName, fileName); head.setCacheControl("must-revalidate, post-check=0, pre-check=0"); return head;}我的角度服務download(url: string): any { let headers = new HttpHeaders(); headers = headers.append('Authorization', 'Bearer ' + this.getToken()); this.http.get(this.API_URL + url, {headers: headers}).subscribe((res) => { const file = new Blob([res], { type: 'application/pdf', }); const a = document.createElement('a'); a.href = this.API_URL + (<any>res)._body; a.target = '_blank'; document.body.appendChild(a); a.click(); return res; }, error => { let alert: any = { title: 'Notify Title', body: 'Notify Body', }; alert.body = error.error.message || JSON.stringify(error.error); alert.title = error.error.error; alert = this.alertService.handleError(error); alert.position = 'rightTop'; console.log(error); this.alertService.notifyError(alert); return error; }); }我已經使用 PostMan 嘗試過我的 API,它的詞很完美,但是在 Angular 中它給了我這個錯誤
1 回答

狐的傳說
TA貢獻1804條經驗 獲得超3個贊
嘗試將內容類型添加到您的請求標頭。你可以試試這個作為一個例子:
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
添加回答
舉報
0/150
提交
取消