@RequestMapping(value="/downloadLogFile")
public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
try {
String filePathToBeServed = //complete file name with path;
File fileToDownload = new File(filePathToBeServed);
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename="+fileName+".txt");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception e){
LOGGER.debug("Request could not be completed at this moment. Please try again.");
e.printStackTrace();
}
}
74
下面的代码为我生成和下载文本文件 .
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDownloadData() throws Exception {
String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
byte[] output = regData.getBytes();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("charset", "utf-8");
responseHeaders.setContentType(MediaType.valueOf("text/html"));
responseHeaders.setContentLength(output.length);
responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");
return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);
}
10 回答
一般来说,当你有
response.getOutputStream()
时,你可以在那里写任何东西 . 您可以将此输出流作为将生成的PDF放入生成器的位置 . 此外,如果您知道要发送的文件类型,则可以进行设置通过使用Spring的内置支持和ResourceHttpMessageConverter,我能够对此进行流式处理 . 如果可以确定mime类型,这将设置content-length和content-type
您应该能够直接在响应上写入文件 . 就像是
然后在
response.getOutputStream()
上将文件写为二进制流 . 记得最后做response.flush()
,应该这样做 .使用Spring 3.0,您可以使用
HttpEntity
返回对象 . 如果使用它,那么控制器不需要HttpServletResponse
对象,因此更容易测试 . 除此之外,这个答案相对于Infeligo的答案 .如果你的pdf框架的返回值是一个字节数组(读取我的答案的第二部分为其他返回值):
If the return type of your PDF Framework (documentBbody) is not already a byte array (也没有
ByteArrayInputStream
)那么首先将它作为字节数组是明智的 NOT . 相反,最好使用:InputStreamResource,
PathResource(自 Spring 季4.0以来)或
FileSystemResource,
FileSystemResource
的示例:如果你:
不希望在发送到响应之前将整个文件加载到
byte[]
中;想要/需要通过
InputStream
发送/下载;希望完全控制发送的Mime类型和文件名;
让其他
@ControllerAdvice
为您挑选例外 .以下代码是您所需要的:
另请注意,为了避免读取整个文件只是为了计算它的长度,你最好先存储它 . 请务必查看InputStreamResource的文档 .
这个代码可以正常工作,从 spring 控制器上点击jsp上的链接自动下载文件 .
下面的代码为我生成和下载文本文件 .
我可以很快想到的是,生成pdf并将其存储在代码中的webapp / downloads / <RANDOM-FILENAME> .pdf中,并使用HttpServletRequest将转发发送到此文件
或者,如果您可以配置您的视图解析器,如,
然后回来
类似下面的东西
您可以显示PDF或下载示例here
以下解决方案适合我