Angular 6从Rest API下载文件 [英] Angular 6 Downloading file from rest api

查看:162
本文介绍了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("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() {

  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下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆