Angular 6 从rest api下载文件

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

问题描述

限时送ChatGPT账号..

我有我的 REST API,我把我的 pdf 文件放在那里,现在我希望我的 angular 应用程序通过我的网络浏览器点击下载它,但我得到了 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: Unexpected token % in JSON at position 0↵ at JSON.parse (

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

推荐答案

我是这样解决的:

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

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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