I am writing application using AngularJS and Spring. I would like to send request to the server and download response returned from controller as a file. In controller I have content of csv file (as string) i.e. 1;2;3;4
(1 row, 4 columns). What is the simplest way to download this response as a file?
Below, I posted my simplified code. In Spring controller:
@RequestMapping(value = "/csv", method = GET)
@ResponseBody
public String getCsvFile() {
return getCsvContent();
}
In javascript (AngularJS)
return $http({method: 'GET', url: 'csv/'});
I was trying to write to the response stream also (below), setting headers, but on client side I always get this content as a string - not as a file to download.
@RequestMapping(value = "/csv", method = GET)
@ResponseBody
public void getCsvFile(HttpServletResponse response) {
response.setContentType("application/csv");
response.setHeader("Content-Disposition", "attachment; filename=file.csv");
response.setContentLength(getCsvContent().getBytes().length);
ServletOutputStream out = response.getOutputStream();
out.write(getCsvContent());
out.flush();
out.close();
}
Does anyone knows how to write controller's method correctly in order to download response as a file on client side?