我知道这是一个很多时间问题。我已经完成了所有答案,但找不到可行的解决方案。 我正在尝试下载pdf文件,jsp中的代码块如下所示
但数据被刷新到浏览器窗口,如下所示
%PDF-1.4%áéëÓ20 obj<> endobj 3 0 obj<> / XObject<> / Font<> >> / MediaBox [0 0 612 792] / Annots [<> >> <> >> <> >> <> >> <> >>] /内容16 0 R>> endobj 16 0 obj<>流xœμ]ÛŽ$ 9}Ÿ¯¨×ŽðUBH,ËðÞB,h-ÿ-HgUwF
请帮助我。
<%
java.io.File file=new java.io.File("C:\\down\\personal\\Card.pdf");
java.io.InputStream in = new java.io.BufferedInputStream(new java.io.FileInputStream(file));
response.setHeader("Content-Disposition", "attachment; filename=empfile.pdf");
response.setContentType("application/pdf");
org.apache.commons.io.IOUtils.copy(in, response.getOutputStream());
response.flushBuffer();
%>
也低于错误
12:57:32,068 ERROR [org.apache.catalina.core.ContainerBase。[jboss.web]。[default-host]。[/ business]。[spring]](http- / 127.0.0.1:8080 -7)JBWEB000236:servle的Servlet.service() spring抛出异常:java.lang.IllegalStateException:已经为此响应调用了JBWEB000028:getOutputStream()
答案 0 :(得分:0)
这就是我试过的
@RequestMapping(value = {&#34; / create&#34;,&#34; / edit&#34;},params =&#34; Action = go1&#34;,produce = MediaType.APPLICATION_OCTET_STREAM_VALUE) @ResponseBody public FileSystemResource getFile(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){ java.io.File file = new java.io.File(&#34; C:\ RAHUL \ personal \ HDFC Bank Credit Card.pdf&#34;); 返回新的FileSystemResource(文件); }
@RequestMapping(value = {"/create","/edit"}, params = "Action=go2")
public ResponseEntity<InputStreamResource> downloadStuff(HttpServletRequest request)
throws IOException {
java.io.File file=new java.io.File("C:\\RAHUL\\personal\\HDFC Bank Credit Card.pdf");
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
respHeaders.setContentLength(12345678);
respHeaders.setContentDispositionFormData("attachment", "fileNameIwant.pdf");
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
@RequestMapping(value = {"/create","/edit"}, params = "Action=go3",method = RequestMethod.GET)
public void download2(HttpServletResponse response,HttpServletRequest request) {
try {
java.io.File file=new java.io.File("C:\\RAHUL\\personal\\HDFC Bank Credit Card.pdf");
InputStream in = new BufferedInputStream(new FileInputStream(file));
response.setHeader("Content-Disposition", "attachment; filename=empfile.pdf");
response.setContentType("application/pdf");
request.setAttribute("override","Y");
org.apache.commons.io.IOUtils.copy(in, response.getOutputStream());
response.flushBuffer();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}