Java 从Outputstream下载PDF文件
我正在使用此方法获取文件Java 从Outputstream下载PDF文件,java,spring,rest,output,Java,Spring,Rest,Output,我正在使用此方法获取文件 @GetMapping(value = "/test", produces = MediaType.APPLICATION_PDF_VALUE) public String test() throws FOPException, IOException { SisDocuments document = documentRepository.getOne(Long.valueOf("801859")); documentService.constr
@GetMapping(value = "/test", produces = MediaType.APPLICATION_PDF_VALUE)
public String test() throws FOPException, IOException {
SisDocuments document = documentRepository.getOne(Long.valueOf("801859"));
documentService.constructDocumentById(document);
return "/connexion";
}
此方法是在我的项目目录中创建一个文件,我不想创建它,我想下载它。典型的方法是将文件作为
InputStream
获取,并将其写入响应的OutputStream
@GetMapping(value = "/test/{idDocument}", produces = MediaType.APPLICATION_PDF_VALUE)
public void test(@PathVariable("idDocument") String idDocument, HttpServletRequest request,
HttpServletResponse response) throws FOPException, IOException {
SisDocuments document = documentRepository.getOne(Long.valueOf(idDocument));
documentService.constructDocumentById(document);
try {
// // get your file as InputStream
File f = new File("employee.pdf");
InputStream is = new FileInputStream(f);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
// copy it to response's OutputStream
response.addHeader("Content-disposition", "attachment; filename=" + "employee.pdf");
response.setContentType("application/pdf");
response.flushBuffer();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
控制器方法不能返回字符串
,实际上它不能返回任何内容:)
要流式传输文件,您必须直接在javax.servlet.http.HttpServletResponse-outputstream
中编写内容,例如:
HttpServletResponse response;
Files.copy( yourPath, response.getOutputStream() );
您的方法必须返回一个字符串
,但我在您的方法中没有看到任何返回
!那是个打字错误。感谢@Halayemanisy您的解决方案是显示文档内容而不是下载文档—只需为此添加适当的响应标题。[请参阅更新的答案]同一问题Buddy文件的导入是什么?!?一个标准的Java1.7+实用程序文件,它只是一个关于如何在outputstream中复制文件内容的示例,顺便说一句,为什么=>?!?
HttpServletResponse response;
Files.copy( yourPath, response.getOutputStream() );