我有我的REST API,我把我的pdf文件放在那里,现在我想我的angular应用程序通过我的web浏览器点击下载它,但我得到了HttpErrorResponse

"JSON中位置0处的意外标记%

"SyntaxError:JSON中位于位置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);});

推荐答案

我决定如下:

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

Typescript相关问答推荐

为什么在TypScript中将类型守护的返回类型写成This is(

Tailwind CSS样式不在Svelte应用程序中呈现

如何使类型只能有来自另一个类型的键,但键可以有一个新值,新键应该抛出一个错误

如果存在ts—mock—imports,我们是否需要typescpt中的IoC容器

键集分页顺序/时间戳上的筛选器,精度不相同

将对象属性转换为InstanceType或原样的强类型方法

泛型函数即使没有提供类型

编剧错误:正在等待Expect(Locator).toBeVisible()

了解类型规则中的关键字

类型脚本满足将布尔类型转换为文字.这正常吗?

嵌套对象的类型

类型脚本可以推断哪个类型作为参数传递到联合类型中吗?

跟踪深度路径时按条件提取嵌套类型

如何从对象或类动态生成类型

有没有办法传递泛型类型数组,以便推断每个元素的泛型类型?

如何避免多个类型参数重复?

定义一个只允许来自另一个类型的特定字符串文字的类型的最佳方式

在ts中获取级联子K类型?

如何为字符串模板文字创建类型保护

是否可以使用元组中对象的键来映射类型