java 下载文件报错getOutputStream() has already been called for this response
public void downFile(String filepath, String filename,HttpServletResponse response) {
response.setContentType("application/x-msdownload");
String fileheader = filename;
try {
byte[] b = fileheader.getBytes("GBK");
fileheader = new String(b, "8859_1");
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
response.setHeader("content-disposition", "attachment; filename=\""
+ fileheader + "\" ");
FileInputStream fileinputstream;
try {
fileinputstream = new FileInputStream(filepath);
response.setCharacterEncoding("UTF-8");
try {
//OutputStream out = response.getOutputStream();
错误在这里,把上面的注了,用下面这行
PrintWriter out = response.getWriter();
但是会出现乱码 一定要子啊PrintWriter out = response.getWriter();下面家上
response.setCharacterEncoding("UTF-8");
int i;
while ((i = fileinputstream.read()) != -1) {
out.write(i);
}
fileinputstream.close();
out.close();
//response.reset();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
错误原因
在tomcat中jsp编译成servlet之后在函数_jspService(HttpServletRequest request, HttpServletResponse response)的最后
有一段这样的代码
finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法是和
response.getOutputStream()相冲突的!所以会出现以上这个异常。
然后当然是要提出解决的办法,其实挺简单的(OutputStream out = response.getOutputStream();换成PrintWriter out = response.getWriter();),