首页 > 解决方案 > 如何使用角度从java接收文件csv

问题描述

我有一个返回 a 的 rest api,file.csv 然后我检查响应是否为200,并且数据也在responsed.body.

但是浏览器没有下载 csv 文件。

这是 API:

ResponseEntity<Resource>  exportCsv() throws IOException {
    /*
     *
     */
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));


    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-disposition", "attachment; filename=sample.csv");
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    return ResponseEntity.ok()
                         .headers(headers)
                         .contentLength(file.length())                 
                .contentType(MediaType.parseMediaType("text/csv"))
                         .body(resource);
}

这是角

this.stickService.exportCsv( this.stickSearch ).subscribe(
  response => this.downloadFile(response),
  err => console.log('Error downloading the file.'  + err.message 
));


downloadFile(data: Response) {
  const blob = new Blob([data], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);
  window.open(url);
}


exportCsv( stickSearch: StickSearch ): Observable<any> {
  const headers = this.oAuthService.putTokenInHeaders(this.headers);

  let params = new HttpParams({encoder: new HttpURIEncoder()});

  if (stickSearch.searchString() !== '') {
    params = params
    .append('search', stickSearch.searchString())
  }

  return this.httpClient.get(this.exportCsvUrl + '/exportCsv',
  {
    responseType: 'text',
    params: params,
    headers
  });
}

我在响应正文中获得了正确的数据。

但是下载失败。 'Error downloading the file.Http failure during parsing for myURL '

感谢您的帮助

它现在工作,这是结果非常感谢!

标签: javaangularspring-boot

解决方案


我可以看到您正在获取服务器提供的输出,然后从该 CSV 构建一个 URL。那将没有必要。如果您只想下载 CSV,那么您所缺少的只是 Java 代码中的以下内容:

headers.add("Content-disposition", "attachment; filename=sample.csv");

一旦有了标头,您就可以摆脱该downloadFile方法,并可能将this.httpClient.get请求更改为window.open.

看看这是否能解决您的问题并在任何一种情况下提供反馈。


推荐阅读