0

I have a Vue application in which I have an "downloadCsv" method. When a button is pressed, this method is invoked and the following rest GET call is made:

@GetMapping(value = "downloadCsv")
public ResponseEntity<Resource> exportSubmitted() throws IOException {

    //Generates CSV file and returns fileName
    String filePath = myService.generateCSV();

    InputStreamResource resource = new InputStreamResource(new FileInputStream(filePath));

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "data.csv" + "\"")
        .body(resource);
}

When I call this endpoint directly, i.e. localhost:8080/downloadCsv in the browser(chrome), the csv is downloaded.

However, when I call this endpoint from within my Vue app on click, i.e.:

  axios.get(endpoint)
            .then(result => {
        const blob = new Blob([result], {type: 'text/csv'});
        FileSaver.saveAs(blob, 'download.csv');
    });

I am unable to have the browser download the file.

What is the correct way to call a rest endpoint that returns a file and download it within the browser in Vue?

Phil
  • 157,677
  • 23
  • 242
  • 245
DevelopingDeveloper
  • 883
  • 1
  • 18
  • 41
  • _"I am unable to have the browser download the file"_ <- can you expand on this? How does it _"not work"_? Are there any errors in your browser console? How is `result` generated? What type is `result`? – Phil Oct 09 '18 at 04:21
  • Can you please read my questions again; I didn't ask you about the HTTP response status – Phil Oct 09 '18 at 04:23
  • @Phil I have updated the question on how result is generated. I have verified in the browser that it is calling the `/downloadCsv` api. – DevelopingDeveloper Oct 09 '18 at 04:30
  • Have you tried setting `responseType: 'blob'` in your Axios request, eg `axios.get(endpoint, { responseType: 'blob' })` – Phil Oct 09 '18 at 05:07
  • Possible duplicate of [Handle file download from ajax post](https://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post) – Phil Oct 09 '18 at 05:31
  • Also see https://github.com/eligrey/FileSaver.js/wiki/Saving-a-remote-file – Phil Oct 09 '18 at 05:32

0 Answers0