我们正在尝试其中一个项目,并尝试下载一份pdf文档。
以下是我们在控制器中的代码
@RequestMapping(value = "/usermanual", method = RequestMethod.GET)
public void getFile(HttpServletRequest req,
HttpServletResponse response) throws IOException
{
try {
// get your file as InputStream
File file = new File(req.getRealPath("/")+"js/loginPage/usermanual.pdf");
InputStream is = new FileInputStream(file);
/*BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File("E:/Backups/p.pdf")));
org.apache.commons.io.IOUtils.copy(is, stream);
stream.close();*/
// Response header
response.setHeader("Content-Disposition", "attachment; filename=123.pdf");
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.setContentType("application/pdf");
response.flushBuffer();
response.getOutputStream().close();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
该文件在E目录中生成,因此文件复制在本地磁盘上没有问题,但在response.getOutputStream中它有一些问题。
结果我们得到了空白的PDF格式。
请在这种情况下提供一些指导。提前谢谢。
答案 0 :(得分:1)
在flush
的{{1}}之前添加close
。
OutputStream
或者如果您使用的是Spring MVC 4.2,则可以使用 response.getOutputStream().flush();
StreamingResponseBody
有关详细信息,请参阅此post