Reputation: 2021
I want to make a Spring Boot endpoint for downloading file. I Have tried this things but the file does not download automatically... I get only file content in the body...
@RequestMapping(value = "/files", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public ResponseEntity<FileSystemResource> getFile(@RequestParam(name = "start") String start) {
return new ResponseEntity<>(new FileSystemResource(myService.makeFile(start)),
HttpStatus.OK);
}
Another one that I have tried is this:
@RequestMapping(value = "/download", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public String download(HttpServletResponse response, @RequestParam(name = "start") String start)
{
response.setContentType("application/force-download");
FileReader fr = new FileReader(myService.makeFile(start));
return IOUtils.toString(fr);
}
I have read that MediaType.APPLICATION_OCTET_STREAM_VALUE will force it to download but nothing happened in my case.
Upvotes: 5
Views: 2739
Reputation: 1471
You are on the right track, you just need to set one response header Content-Disposition
to attachment; filename=YOUR_FILE_NAME
.
Try This:
@RequestMapping(value = "/files", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public FileSystemResource getFile(@RequestParam(name = "start") String start, HttpServletResponse response) {
response.setHeader("Content-Disposition", "attachment; filename=" + "YOUR_FILE_NAME");
return new FileSystemResource(myService.makeFile(start));
}
Upvotes: 3