我在使用 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
提交
取消