【问题标题】:Download file using spring RestFul service使用 spring RestFul 服务下载文件
【发布时间】:2017-07-18 06:50:28
【问题描述】:

我想从网站下载 PDF。 PDF需要在代码中生成,我认为这将是freemarker和iText等PDF生成框架的组合。有更好的方法吗?

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

【问题讨论】:

    标签: spring


    【解决方案1】:
    @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");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-27
      • 2012-04-23
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 2012-10-08
      • 2014-11-11
      • 2019-01-30
      相关资源
      最近更新 更多