Downloading a file from spring controllers

前端 未结 14 894
渐次进展
渐次进展 2020-11-22 01:06

I have a requirement where I need to download a PDF from the website. The PDF needs to be generated within the code, which I thought would be a combination of freemarker and

14条回答
  •  既然无缘
    2020-11-22 01:46

    @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");
    

提交回复
热议问题