Search code examples
java-iofileinputstreamfileoutputstream

Downloaded XLS file using servletOutputStream showing invalid file content. Please advice to fix it


I am using below code to download and show the xls file from my webapp. file downloading with invalid characters (like 䡗ⰱㅂ〬ⰱ). Please let know what I am missing in this code.

        String contentDisposition = "attachment";
        String fileName = "Test.xls";
        String path = "/xxx/yyy";
        final int BUFFER = 1024; 
        byte servletBytes[] = new byte[BUFFER];
        ServletOutputStream out = response.getOutputStream();
        FileInputStream fis = new FileInputStream(new File(path));

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        int count = 0;
        while ((count = fis.read(servletBytes)) > 0) {
            bout.write(servletBytes, 0, count);
        }

        fis.close();

        servletBytes = bout.toByteArray();
        bout.close();
        out.write(servletBytes);
        response.setContentType("Application/vnd.ms-excel;charset=UTF-8");

        if (contentDisposition.length() > 0) {
            response.setHeader("Content-Disposition", contentDisposition + ";filename=" + fileName);
        }

        out.flush();
        out.close();
        if (fis != null) {
            fis.close();
        }

        if (bout != null) {
            bout.close();
        }

Solution

  • Setting content-Disposition and filename should be before writing in Stream and also I optimized the code. So then we can avoid issue : File downloading with Servlet Name.

        String contentDisposition = "attachment";
        String path = "/test/ship.xls";
        byte servletBytes[] = new byte[BUFFER];
        ServletOutputStream out = response.getOutputStream();
        FileInputStream fis = new FileInputStream(new File(path));
        response.setContentType("Application/vnd.ms-excel;charset=UTF-8");
        if (contentDisposition.length() > 0) {
            response.setHeader("Content-Disposition", contentDisposition + ";filename=" + 
            new File(path).getName());
        }
        int count = 0;
        while ((count = fis.read(servletBytes)) > 0) {
            out.write(servletBytes, 0, count);
        }
        fis.close();
        out.flush();
        out.close();