java - 使用 Angular 6 和 Spring Rest API 下载文件
问题描述
我在使用 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);
}
方法 getHeader
public 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 中它给了我这个错误
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/api/projects/print/1", ok: false, …}
error: {error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "%PDF-1.4↵%����↵3 0 obj↵<</Filter/FlateDecode/Lengt…25f1>]/Root 8 0 R/Size 10>>↵startxref↵1049↵%%EOF↵"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/api/projects/print/1"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/api/projects/print/1"
解决方案
尝试将内容类型添加到您的请求标头。你可以试试这个作为一个例子:
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
推荐阅读
- angular - Firestore 允许在一个集合中创建两个具有相同 ID 的单独文档
- pandas - 根据 df.A 和 df.B 中的比较值填充 df.A 中的列
- html - 当我将文件托管到我的网站时,媒体查询将不起作用
- modx-revolution - 使用 getImageList 片段将电视值传递给占位符
- dictionary - Haskell Data.Map 查找并同时删除
- mysql - 我已将 MySql 数据库与 SQL Developer 连接,但无法更新表或存储过程
- javascript - 是否可以限制 keyup 的最大日期?
- android - iOS 和 Android 应用旧版本 - 禁止使用
- char - 如何通过公式计算 Apache OpenOffice Calc 中单元格大写字母的长度?
- r - 检查特定组中是否存在字符并在 R 中创建新列