Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive file csv from java with angular

I have a rest api which returns a file.csv and then I check that the response is 200, and datas are also in responsed.body.

But the brower didn't download the csv file.

Here is the 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);
}

Here is the Angular

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

I got correct data at response body.

But the download failed. 'Error downloading the file.Http failure during parsing for myURL '

Thanks for helping

It work now, this is consequence Thanks a lot !

like image 966
a4fz067lu Avatar asked Dec 29 '25 21:12

a4fz067lu


1 Answers

I can see that you are taking the output provided by the server and then building an URL off that CSV. That won't be necessary. If you just want to download the CSV, then all you are missing is the following in your Java code:

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

Once you have the header in place, you can get rid of the downloadFile method and probably change the this.httpClient.get request into a window.open.

See if this solves your problem and provide feedback in either case.

like image 109
Filippo Possenti Avatar answered Dec 31 '25 11:12

Filippo Possenti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!