文件下载后台报错IllegalStateException: getOutputStream() has already been called

java.lang.IllegalStateException: getOutputStream() has already been called

 1 <%@page language="java" contentType="text/html; charset=UTF-8"%>
 2 <%@page   import="java.util.*,java.io.*"%>
 3 <html>
 4 <head>
 5 <title>下载页面</title>
 6 </head>
 7 
 8 <body>
 9 <%
10 response.reset();  //记住要记住reset浏览器清空缓存,否则可能会出现乱码情况
11 
12 OutputStream o=response.getOutputStream();
13 
14 ResourceBundle res = ResourceBundle.getBundle("test");    //test.properties
15 String XLSFile = res.getString("tempFileRootPath") + "/excel";
16 File fileLoad=new File(XLSFile,"temp.xls");
17 
18 if(fileLoad.exists()) {
19     response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode("filename文件名", "UTF-8")+".xls");//文件中文名UTF-8
20     response.setContentType("application/vnd.ms-excel");
21     long fileLength=fileLoad.length();
22     String length=String.valueOf(fileLength);
23     response.setHeader("Content_Length",length);
24     
25     FileInputStream in = new FileInputStream(fileLoad);
26     OutputStream o = null;
27     try{
28     in = new FileInputStream(fileLoad);
29     
30     o = response.getOutputStream();
31     out.clear();
32     out = pageContext.pushBody();    // 
33     
34     int n=0;
35     byte b[]=new byte[500];
36     
37     while((n=in.read(b))!=-1) {
38         o.write(b,0,n);
39     }
40     o.flush();
41     
42     } catch (Exception e) {
43         out.write("文件导出异常" + e.toString());
44     } finally {
45         if(in != null) {
46             try {
47                 in.close();
48             } catch(Exception e) {}
49         }
50         if(o != null) {
51             try {
52                 o.close();
53             } catch(Exception e) {}
54         }
55     }
56 } else {
57     out.write("未找到导出的临时文件");
58 }
59 
60 %>
61 
62 </body>
63 </html>

异常是由于冲突导致的,在使用完response.getOutputStream()的后面加上两句(标黄):

out.clear();
out = pageContext.pushBody();

 

上一篇:Batch Normalization原理理解与作用


下一篇:卡尔曼滤波与组合导航原理——严恭敏(02)