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 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端