Angular 6从Rest API下载文件

编程入门 行业动态 更新时间:2024-10-18 22:25:25
本文介绍了Angular 6从Rest API下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有我的REST API,我在其中放置了pdf文件,现在我希望我的有角度的应用程序可以通过Web浏览器点击下载,但我却收到HttpErrorResponse

I have my REST API where I put my pdf file, now I want my angular app to download it on click via my web browser but I got HttpErrorResponse

"JSON在位置0处出现意外令牌%"

"Unexpected token % in JSON at position 0"

"SyntaxError:JSON.parse中位置0↵的JSON中的意外令牌%(

"SyntaxError: Unexpected token % in JSON at position 0↵ at JSON.parse (

这是我的终点

@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("localhost:9989/api/download/help/pdf2", httpOptions);

}

和调用

this.downloadService.getPdf() .subscribe((resultBlob: Blob) => { var downloadURL = URL.createObjectURL(resultBlob); window.open(downloadURL);});

推荐答案

我如下解决了该问题:

// headerponent.ts this.downloadService.getPdf().subscribe((data) => { this.blob = new Blob([data], {type: 'application/pdf'}); var downloadURL = window.URL.createObjectURL(data); var link = document.createElement('a'); link.href = downloadURL; link.download = "help.pdf"; link.click(); }); //download.service.ts getPdf() { this.authKey = localStorage.getItem('jwt_token'); const httpOptions = { responseType: 'blob' as 'json', headers: new HttpHeaders({ 'Authorization': this.authKey, }) }; return this.http.get(`${this.BASE_URL}/help/pdf`, httpOptions); }

更多推荐

Angular 6从Rest API下载文件

本文发布于:2023-11-28 10:00:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641943.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   Angular   Rest   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!