在jsp下载文件如jpeg、word等使用getOutputStream()时出现异常

          在JavaEE中使用getOutputStream()方法来下载文件时,我的YingjiAction.java中的部分代码如下:

if(picpath.equals("null"))
        {
         req.setAttribute("isNull",1);
        }
        else{
         req.setAttribute("isNull",0);
        FileInputStream inf=new FileInputStream(picpath);

        req.setAttribute("isNull",0);
        rep.setContentType("image/jpeg");
        OutputStream outf = rep.getOutputStream();
    
       
        byte[] buffer=new byte[1024];

         int len=0;
   while((len=inf.read(buffer))>0)
   {
   outf.write(buffer,0,len);
   }
   inf.close();
   outf.close();    
        }
     return Action.SUCCESS;

其中使用了HttpRequest来调用了getOutputStream()方法,用tomcat发布工程后调用此方法会出现“getOutputStream() has already been called for this response”的异常提示。

 

通过查阅相关资料才得知,这是运用流方法冲突导致的,在此调用过程中,我们使用了getOutputStream()方法进行流输出,在相关JSP页面中页面自动调用了JspWriter的out()方法,通过查看Servlet的API得知,这两个流是不能同时使用的。

但是也有解决的办法,解决办法不是在java代码中操作,而是在流输出的jsp页面的最后加上两句如下代码

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

如此问题便可解决

你可能感兴趣的:(在jsp下载文件如jpeg、word等使用getOutputStream()时出现异常)