2017-07-18 104 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」);