I want to make a rest API controller (spring boot) that when petitioned with a get will allow me to download an Excel file. Currently I have this endpoint:
@RequestMapping(value = "/download.xls", method = RequestMethod.GET)
public ResponseEntity Survey_Reports(@RequestParam(value = "evaluated") String evaluated){
return surveyService.getSurveysFile(evaluated);
}
which ultimately calls to this method:
public static ResponseEntity getDownloadResponse() {
File file2Upload = new File("Survey_Reports.xls");
Path path = Paths.get(file2Upload.getAbsolutePath());
ByteArrayResource resource = null;
try {
resource = new ByteArrayResource(Files.readAllBytes(path));
} catch (IOException e) {
logger.error("there was an error getting the file bytes ", e);
}
return ResponseEntity.ok()
.contentLength(file2Upload.length())
//this line doesn't seem to work as I set the file format in the controller request mapping
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(resource);
}
everything seems to work semi-fine as I get the download.xls(as the mapping) file correctly, but now I want to make the downloaded file have some specific name like: evaluatedName.xls or userDateEndDate.xls or some other stuff, is there a way to edit the response entity to do so? so that I don't have to name the mapping "download.xls"
In context of HttpServletResponse response you can do this like this
response.setContentType("application/csv");
response.setHeader("Content-Disposition", "attachment; filename=" + csvName);
and for ResponseEntity i assume you can use something like this:
ResponseEntity.ok().header("Content-Disposition","attachment; filename=" + csvName );