使用 servletOutputStream 下载的 XLS 文件显示无效的文件内容。请建议修复它

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

我正在使用以下代码从我的网络应用程序下载并显示 xls 文件。下载包含无效字符的文件(如䡗ⰱㅂ〬ⰱ)。请让我知道这段代码中缺少什么。

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

下面的代码适合我。已下载文件内容,但带有 servlet 文件名。请帮忙解决

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

设置content-Disposition和filename应该在写入Stream之前,我也优化了代码。 这样我们就可以避免问题:使用 Servlet 名称下载文件。

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