【问题标题】:Angular Spring Download JSON FileAngular Spring 下载 JSON 文件
【发布时间】:2022-01-09 22:33:41
【问题描述】:

我可以在不同的端口上使用这种方法吗?它在端口:8080 上工作,我可以下载文件,但在:4200 上,我只看到日志,仅此而已。

方法:

@GetMapping("/downloadJson")
    public ResponseEntity<byte[]> downloadJsonFile() {
        List<Wine> wines = wineService.findAllWines();

        String wineJsonString = jsonExporter.export(wines);

        byte[] wineJsonBytes = wineJsonString.getBytes();

        return ResponseEntity
                .ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=wines.json")
                .contentType(MediaType.APPLICATION_JSON)
                .body(wineJsonBytes);
    }

HTML:

 <a class="nav-link" (click)="downloadFile()">Download<span class="sr-only">(current)</span></a>

服务:

public downloadJsonFile(): Observable<any> {
return this.http.get<any>(`${this.apiServerUrl}/wine/downloadJson`)

}

组件:

public downloadFile() {
    this.wineService.downloadJsonFile().subscribe();
  }

【问题讨论】:

  • 这是一个有角度的前端应用程序吗?如果是这样,您需要通过节点服务器将您的请求代理到您的 springboot 应用程序。
  • 是的,有角度的前端应用程序。我该怎么做或者我在哪里可以读到呢?

标签: java angular spring-boot


【解决方案1】:

我不得不更改 component.ts 中的下载方法:

    public downloadFile(): void {
    this.wineService
      .download()
      .subscribe(blob => saveAs(blob, 'wine.json'));
  }

服务:

    public download(): Observable<Blob> {
    return this.http.get(`${environment.apiBaseUrl}/wine/downloadJson`, {
      responseType: 'blob'
    });
  }

要在组件中使用“saveAs”,我必须下载新包:

npm install --save file-saver

并在 app.component.ts 中导入

import { saveAs } from 'file-saver';

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    相关资源
    最近更新 更多