从弹簧控制器下载文件 [英] Downloading a file from spring controllers
问题描述
我需要从网站下载PDF档案。 PDF需要在代码中生成,我认为这将是freemarker和一个PDF生成框架(如iText)的组合。任何更好的方法?
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控制器下载文件?
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");
}
}
一般来说, code> 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屋!