簡體   English   中英

如何使用角度從java接收文件csv

[英]How to receive file csv from java with angular

我有一個返回file.csv的 rest api,然后我檢查響應是否為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 '

謝謝你的幫助

它現在起作用了,這是結果 非常感謝!

我可以看到您正在獲取服務器提供的輸出,然后從該 CSV 構建一個 URL。 那將是沒有必要的。 如果您只想下載 CSV,那么您所缺少的只是 Java 代碼中的以下內容:

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

一旦你有了標題,你就可以擺脫downloadFile方法,並且可能將this.httpClient.get請求更改為window.open

看看這是否能解決您的問題並在任一情況下提供反饋。

默認情況下HttpClient期望來自服務器的數據采用json格式。 Angular 嘗試將文本正文解析為 json。 這導致了例外。 當您請求數據時,在stickService ,您必須將 type 或 result 指定為text

constructor (private httpClient: HttpClient){
}

public exportCsv(stickSearch: any) {
    return httpClient.get('http://someurl', {responseType: 'text'});
}

您使用window.open(url)另一點。 大多數瀏覽器默認阻止彈出窗口。 所以也許使用錨元素會更好。

downloadFile(data: Response) {
    const blob = new Blob([data], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const anchor = document.createElement('a');
    anchor.download = 'myfile.txt'; // here you can specify file name
    anchor.href = url;
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
}

這是我用於此功能的。 首先,使用“接受”標頭。 其次,設置 responseType 為 'text',默認為 'json'。 三、下載代碼。

getCsv(): Observable<any> {
  let headers = new HttpHeaders();
  headers = headers.set('Accept', 'application/csv');

  return this.http.get('SOME__URL', {
    headers: headers,
    responseType: 'text'
  });
}

exportReportCSV() {
  getCsv().subscribe( response => {
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(new Blob([response], {type: 'text/csv'}));
    link.download = this.report.name + '.csv';
    link.click();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM