2017-07-18 115 views
0

我想从网站上下载PDF文件。 PDF需要在代码中生成,我认为这是Freemarker和iText等PDF生成框架的结合。有更好的方法吗?使用spring RestFul服务下载文件

但是,主要问题是,我不知道如何让用户通过Spring Controller下载文件?

回答

2
@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”);