abosten_love 2009-12-09 19:37
浏览 701
已采纳

文件下载时异常: getOutputStream() has already been called for this response

           [color=red]  Stirng fileName = request.getParameter("fileName");//Redirect();[/color]
    [color=red]//String fileName = request.getAttribute("fileName").toString();//forward()[/color]
    try{
                File file = new File(filePath);
                FileInputStream bis = new FileInputStream(file);
                response.reset();
                response.setContentType("APPLICATION/OCTET-STREAM; charset=utf-8");
                response.setHeader("Content-disposition", "attachment; filename= " + fileName);
                /*response.setHeader("Content-disposition","filename=" + fileName);*/
                response.setContentLength((int) file.length());

                OutputStream bos = response.getOutputStream();

                byte[] buff = new byte[1024];
                int readCount = 0;
                readCount = bis.read(buff);
                while (readCount != -1)
                {
                    bos.write(buff, 0, readCount);
                    readCount = bis.read(buff);
                }
                bos.flush();
                if(bis != null)
                {
                    bis.close();
                }
                if(bos != null)
                {
                    bos.close();
                }

            }
            catch (Throwable e)
            {
                //e.printStackTrace();
            }finally{
                out.clear();
                out = pageContext.pushBody();
            }      

如果 是重定向到下载页面 不会出异常 但是如果forward(),
依然报getOutputStream() has already been called for this response

  • 写回答

1条回答 默认 最新

  • javabull 2009-12-09 20:01
    关注

    getOutputStream()和getWriter()这两个方法不能在一个请求内同时使用,如果使用forward,这时将要跳转到的页面是要用getWriter方法获得输出流把页面内容发送到浏览器,但之前以经使用了getOutputStream,而且是同一请求,所以出错了,使用redirect因为是两个不同的请求,所以不会出错。下载时你可以打开新页面来下载,这样下载完了之前页面也还在。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记