从弹簧控制器下载文件 [英] Downloading a file from spring controllers

查看:25
本文介绍了从弹簧控制器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,需要从网站下载 PDF.PDF 需要在代码中生成,我认为这将是 freemarker 和像 iText 这样的 PDF 生成框架的组合.有什么更好的办法吗?

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 a PDF generation framework like iText. Any better way?

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

However, my main problem is how do I allow the user to download a file through a Spring Controller?

推荐答案

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

}

一般来说,当你有 response.getOutputStream() 时,你可以在那里写任何东西.您可以将此输出流作为将生成的 PDF 放入生成器的位置传递.此外,如果您知道要发送的文件类型,则可以设置

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

这篇关于从弹簧控制器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆