我有我的 REST API,我在其中放置了我的 pdf 文件,现在我希望我的 angular 应用程序通过我的网络浏览器单击下载它,但我得到了 HttpErrorResponse
“位置 0 处 JSON 中的意外标记 %”
“SyntaxError:JSON.parse 中位置 0↵ 处 JSON 中的意外标记 %(
这是我的终点
@GetMapping("/help/pdf2")
public ResponseEntity<InputStreamResource> getPdf2(){
Resource resource = new ClassPathResource("/pdf-sample.pdf");
long r = 0;
InputStream is=null;
try {
is = resource.getInputStream();
r = resource.contentLength();
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok().contentLength(r)
.contentType(MediaType.parseMediaType("application/pdf"))
.body(new InputStreamResource(is));
}
这是我的服务
getPdf() {
this.authKey = localStorage.getItem('jwt_token');
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/pdf',
'Authorization' : this.authKey,
responseType : 'blob',
Accept : 'application/pdf',
observe : 'response'
})
};
return this.http
.get("http://localhost:9989/api/download/help/pdf2", httpOptions);
}
和调用
this.downloadService.getPdf()
.subscribe((resultBlob: Blob) => {
var downloadURL = URL.createObjectURL(resultBlob);
window.open(downloadURL);});
原文由 gmexo 发布,翻译遵循 CC BY-SA 4.0 许可协议
我解决了它如下: