public class DownloadAction extends Action {
//问题:下载文件时,后台老是抛出异常:
//getOutputStream() has already been called for this response
//不知这段代码哪里出了问题没有.谢谢大家的帮忙.
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String oldFileName=request.getParameter("oldFileName");
//弹出一个框框
response.setContentType("text/html;charset=utf-8");
//设置一个头,告诉浏览器有文件要下载 对中文要进行url编码
try {
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldFileName,"utf-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String newFileName=request.getParameter("newFileName");
String fileAllPath=this.getServlet().getServletContext().getRealPath("/file")+"\\"+newFileName;
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream(fileAllPath);
os=response.getOutputStream();
int len;
byte[] buf=new byte[1024];
while((len=is.read(buf))>0){
os.write(buf,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(null!=is){
is.close();
}
if(null!=os){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return mapping.findForward("back");
}
}