错误:Java中的IllegalStateException。在提交响应后无法转发

时间:2016-09-01 06:38:09

标签: java file servlets tomcat8 downloading

需要帮助,

我正在努力下载Java Servlet中的文件,文件下载后无法将请求发送到页面。

当我尝试将请求转发到页面时,文件已成功下载并获取illegalStateException。

这是代码

public void fileDownload(String stringFileToDownload, HttpServletResponse response) throws Exception{
    FileInputStream inStream = null;
    OutputStream outStream = null;
        try{            
            File downloadFile = new File(stringFileToDownload); //Reads input file
            inStream = new FileInputStream(downloadFile);
            response.setContentType("application/zip-compressed"); //MIME type of the file
            response.setContentLength((int) downloadFile.length());
            response.setHeader("Content-Disposition", "attachment; filename=Time.zip");
            //response's output stream
            outStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
        }
        catch(Exception ex){
            throw ex;
        }
        finally{
            //response.flushBuffer();
            try{
                if(inStream != null){
                    inStream.close();
                }
                if(outStream != null){
                    //outStream.flush();
                    outStream.close();
                }   
            }
            catch(Exception ex){
                throw ex;
            }
        }
    }

我从servlet调用了这个方法;从servlet重定向到另一个页面

致电代码:

FileDownloadFromWeb fileDownloadFromWeb = new FileDownloadFromWeb(); 
fileDownloadFromWeb.fileDownload(stringarchiveFile, response); //Allow to download 
Request Dispatcher objRequestDispatcher = request.getRequestDispatcher(objProperties.getProperty("SUCC‌​ESS_DOWNLOAD")); 
objRequestDispatcher.forward(request, response);

1 个答案:

答案 0 :(得分:1)

这里当您写入输出流时,响应将被提交(outStream.write(buffer, 0, bytesRead);),然后如果您尝试使用request.forward(),它将会出错。

此问题的解决方案是将您的文件内容设置为请求参数中的对象,而不是在jsp中使用它或使用重定向而不是转发

可能您的问题可以通过单独的servlet进行文件下载来修复,请参阅此after download a image ,i want to redirect on another page, but not able to