Search code examples
javafileservletstomcat8download

Error : IllegalStateException in Java. Cannot forward after response has been committed


Help needed,

I am working for to download the file in Java Servlet and after the file download can't send the request to page.

File is downloaded successfully and getting the illegalStateException when I try forward the request to the page.

here is the code

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;
            }
        }
    }

I called this method from servlet; redirecting from the servlet to the another page

Calling code:

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);

Solution

  • Here when you write to output stream response will be committed ( outStream.write(buffer, 0, bytesRead); ) and then if you try to use request.forward() it will defiantly throw error.

    solution to this problem is to set your file content as object in request parameter and than use it in jsp or use redirect rather than forward

    probably your problem can be fixed by taking separate servlet for file download refer this after download a image ,i want to redirect on another page, but not able to