rest - Angular 6从rest api下载文件

标签 rest typescript angular6

我有我的 REST API,我把我的 pdf 文件放在那里,现在我希望我的角度应用程序通过我的网络浏览器点击下载它,但我得到了 HttpErrorResponse

“位置 0 的 JSON 中的意外标记 %”

“SyntaxError: JSON.parse 位置 0↵ 中的意外标记 % (

这是我的终点

    @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);});

最佳答案

我是这样解决的:

// header.component.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() {

  const httpOptions = {
    responseType: 'blob' as 'json')
  };

  return this.http.get(`${this.BASE_URL}/help/pdf`, httpOptions);
}

关于rest - Angular 6从rest api下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52154874/

相关文章:

javascript - 让 JavaScript 随机报价生成器每天只生成一个报价

cordova - ionic 4 Cordova cordova-plugin-facebook4 : Property 'provide' is missing in type 'FacebookOriginal'

node.js - Node Azure 功能在本地运行,但在 Azure 中不起作用

java - Jersey - 在运行时设置 REST 响应编码

java - 使用 JAX-RS 和 Jackson 将 JPA 实体转换为 REST 表示的最佳方法

javascript - 如何在API中包含字段而不在数据库中添加键/值?

TypeScript:公共(public)类扩展私有(private)类:不可能?

javascript - 错误类型错误 : value. forEach 不是函数

angular-material - Angular mat-sidenav 属性 isHandset$ |异步解释

android - Django REST框架: Directly display on results list in GenericView