java.lang.IllegalStateException: getOutputStream() has already been called for this respons 简单解决办法


今天在使用struts2 进行文件下载是,总报错:

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

......

 

解决办法:

  把对应的action的返回设置为空,即可轻松解决。

例如:

public class DownloadFileAction extends ActionSupport implements
        ServletRequestAware, ServletResponseAware {
    
    /**
     * 
     */
    private static final long serialVersionUID = -7448748577778248376L;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private String savePath;
    
    @Override
    public String execute() throws Exception {
        
        String fileName=request.getParameter("fileName");
        String fullPath=getSavePath()+"//"+fileName;
        fileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");
        InputStream is=new FileInputStream(fullPath);
        int len=0;
        byte []buffers=new byte[1024];
        response.reset();
        response.setContentType("application/x-msdownload");
        response.addHeader("Content-Disposition", "attachment;filename=\""+fileName+"\"");
        OutputStream os = null;
        //把文件内容通过输出流打印到页面上供下载
        while((len=is.read(buffers))!=-1){
            os=response.getOutputStream();
            os.write(buffers, 0, len);    
        }
        
        is.close();
        os.flush();
        //return SUCCESS; //会报错:java.lang.IllegalStateException: getOutputStream() has already been called for this respons
        return null;//ok
    }
    public void setServletRequest(HttpServletRequest req) {
        this.request=req;
    }
    public void setServletResponse(HttpServletResponse resp) {
        this.response=resp;
    }
    @SuppressWarnings("deprecation")
    public String getSavePath() {
        return request.getRealPath(savePath);
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
    
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM