Downloading a file from spring controllers Downloading a file from spring controllers java java

Downloading a file from spring controllers


@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)public void getFile(    @PathVariable("file_name") String fileName,     HttpServletResponse response) {    try {      // get your file as InputStream      InputStream is = ...;      // copy it to response's OutputStream      org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());      response.flushBuffer();    } catch (IOException ex) {      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);      throw new RuntimeException("IOError writing file to output stream");    }}

Generally speaking, when you have response.getOutputStream(), you can write anything there. You can pass this output stream as a place to put generated PDF to your generator. Also, if you know what file type you are sending, you can set

response.setContentType("application/pdf");


I was able to stream line this by using the built in support in Spring with it's ResourceHttpMessageConverter. This will set the content-length and content-type if it can determine the mime-type

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)@ResponseBodypublic FileSystemResource getFile(@PathVariable("file_name") String fileName) {    return new FileSystemResource(myService.getFileFor(fileName)); }


You should be able to write the file on the response directly. Something like

response.setContentType("application/pdf");      response.setHeader("Content-Disposition", "attachment; filename=\"somefile.pdf\""); 

and then write the file as a binary stream on response.getOutputStream(). Remember to do response.flush() at the end and that should do it.