使用SpringRESTful服务下载文件

使用SpringRESTful服务下载文件,spring,Spring,我想从网站上下载一份PDF。PDF需要在代码中生成,我认为这是freemarker和像iText这样的PDF生成框架的组合。还有更好的办法吗 然而,主要的问题是,我不知道如何允许用户通过Spring控制器下载文件 @RequestMapping(value = "/downlaod/{fileName}", method = RequestMethod.GET) public void getFile( @PathVariable("fileName") String fileName,

我想从网站上下载一份PDF。PDF需要在代码中生成,我认为这是freemarker和像iText这样的PDF生成框架的组合。还有更好的办法吗

然而,主要的问题是,我不知道如何允许用户通过Spring控制器下载文件

@RequestMapping(value = "/downlaod/{fileName}", method = RequestMethod.GET)
public void getFile(
    @PathVariable("fileName") String fileName, 
    HttpServletResponse response) {
    try {

      InputStream is = ...;  // get uploaded file using InputStream 

      org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());      // copy this to response's OutputStream
      response.flushBuffer();
    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
      throw new RuntimeException("IOError to writing file on output stream");
    }

}
如果您有response.getOutputStream(),则可以将所需内容写入其中。您已将此输出流作为放置生成的PDF的位置传递。您还可以设置

response.setContentType(“application/pdf”)

如果您有response.getOutputStream(),则可以将所需内容写入其中。您已将此输出流作为放置生成的PDF的位置传递。您还可以设置

response.setContentType(“application/pdf”)