尝试使用 Struts 6.3.0.2 和 Java 下载时二进制文件被损坏

问题描述 投票:0回答:1

从 struts2 升级到 struts 6.3.0.2 后,当我尝试从我的应用程序下载 pdf 和 doc-x 文件时,该文件已损坏。当我上传到应用程序后从应用程序下载pdf文件时,我无法打开pdf文件。对于 doc-x 文件,它显示系统无法处理您的请求,这是错误文件中的自定义错误。控制台显示文件已下载成功,但仍无法打开doc-x文件。

这是我升级前的原始代码


import java.io.*;
import java.nio.file.Files;
import java.util.ResourceBundle;

public void downloadAttach(){
    try {
        String filename = DotsFormUtil.cleanStringFile(request.getParameter("filename"));
        String realname = DotsFormUtil.cleanStringFile(request.getParameter("name"));

        HttpSession session = (HttpSession) request.getSession();
        String strDotsIdToken = (String) session.getAttribute("strDotsIdToken");

        try{
            if(strDotsIdToken == null || !strDotsIdToken.equals(filename.split("_")[0]))
                logger.error("strDotsIdToken is null or strDotsIdToken is not equal and Exception is thrown");
        }catch (Exception e){
            logger.info(e);
        }
        try {
            if(filename!= null){
               ServletOutputStream out = null;
               FileInputStream fi = null;
                try {
                    ResourceBundle bundle = ResourceBundle.getBundle("resources.dotsDisplay");
                    String strDirectory=DotsFormUtil.cleanpString(bundle.getString("dots.attachments.path"));
                    File f= new File(FilenameUtils.normalize(DotsFormUtil.cleanString(strDirectory+File.separator + filename)));
                    String pattern = "[a-zA-Z0-9]{1,50}\\.[a-zA-Z0-9]{1,10}";
                    if(realname.matches(pattern)){

                        response.setHeader("Content-Disposition","attachment; fileName=" +realname);
                    }
                    response.addHeader("Content-Transfer-Encoding","base64");

                            out = response.getOutputStream();
                        fi= new FileInputStream(f);
                        byte[] buffer = new byte[(int)f.length()];

                        int readInt=fi.read(buffer);
                        try{
                            if(readInt != -1){
                                out.write(buffer);
                                out.flush();
                            }
                        }catch (Exception e){
                            logger.info(e);
                        }
                } catch (FileNotFoundException e){
                    e.printStackTrace();
                    logger.info("File not found error" + filename);
                    logger.error(e.getMessage());
                }catch (IOException e){
                    logger.info("error in reading file:" + filename);
                }finally {
                    if(out != null) safeClose(out);
                    if(fi != null) safeClose(fi);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        logger.info("successfully download attachment file");
    }catch (Exception e){
        e.printStackTrace();

    }
}

    public static String cleanStringFile(String- aString){
        if(aString==null) return null;
        String cleanString = "";
        char cleanChar = '\0';
        for(int i=0; i<aString.length(); i++){
            cleanChar = cleanCharFile(aString.charAt(i));
            if(cleanChar != '\0') cleanString+=cleanChar;
        }
        return cleanString;
    }

    private static char cleanCharFile(char aChar){
        for(int i = 48; i<58; ++i){
            if(aChar ==i) return (char) i;
        }
        for(int i = 65; i<91; ++i){
            if(aChar ==i) return (char) i;
        }
        for(int i = 97; i<123; ++i){
            if(aChar ==i) return (char) i;
        }

        switch (aChar){
            case '.':
                return '.';
            case '_':
                return '_';
            case '-':
                return '-';
            case '!':
                return '!';
        }
        return '\0';
    }

这是我编辑的代码,但我仍然无法打开下载的 pdf 和 doc-x 文件

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.nio.file.Files;
    import java.nio.file.Path;

    public class getDotsMissionAction {

        public void downloadAttach() {
            // Your existing code...

            try {
                if (filename != null) {
                    try {
                        ResourceBundle bundle = ResourceBundle.getBundle("resources.dotsDisplay");
                        String strDirectory =  DotsFormUtil.cleanString(bundle.getString("dots.attachments.path"));
                        File f = new File(strDirectory + File.separator + filename);
                        String pattern = "[a-zA-Z0-9]{1,50}\\.[a-zA-Z0-9]{1,10}";
                        if (realname.matches(pattern)) {
                            response.reset();
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("application/pdf");
                            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                            response.setHeader("Content-Disposition", "attachment; fileName=" + realname);

                            try (FileInputStream fis = new FileInputStream(f);
                                 OutputStream out2 = response.getOutputStream()) {
                                byte[] buffer = new byte[1024];
                                int bytesRead;
                                while ((bytesRead = fis.read(buffer)) != -1) {
                                    out2.write(buffer, 0, bytesRead);
                                }
                            }
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
            logger.info("successfully download attachment file");
        }

        import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.servlet.http.HttpServletResponse;

        public class getDotsMissionAction {

            public void downloadAttach(HttpServletResponse response) {
                // Your existing code...

                try {
                    if (filename != null) {
                        ResourceBundle bundle = ResourceBundle.getBundle("resources.dotsDisplay");
                        String strDirectory = DotsFormUtil.cleanString(bundle.getString("dots.attachments.path"));
                        File f = new File(strDirectory + File.separator + filename);
                        String pattern = "[a-zA-Z0-9]{1,50}\\.[a-zA-Z0-9]{1,10}";
                        if (realname.matches(pattern)) {
                            response.reset();
                            response.setCharacterEncoding("UTF-8");

                            // Determine content type based on file extension
                            String contentType;
                            if (realname.toLowerCase().endsWith(".pdf")) {
                                contentType = "application/pdf";
                            } else if (realname.toLowerCase().endsWith(".docx")) {
                                contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                            } else {
                                // Add more content types as needed
                                contentType = "application/octet-stream"; // Default to binary
                            }
                            response.setContentType(contentType);
                            response.setHeader("Content-Disposition", "attachment; filename=" + realname);

                            try (FileInputStream fis = new FileInputStream(f);
                                 OutputStream out2 = response.getOutputStream()) {
                                byte[] buffer = new byte[1024];
                                int bytesRead;
                                while ((bytesRead = fis.read(buffer)) != -1) {
                                    out2.write(buffer, 0, bytesRead);
                                }
                            }
                        } else {
                            // Handle invalid filename pattern
                            // For example: Log an error, return a response indicating invalid file, etc.
                        }
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
                logger.info("successfully download attachment file");
            }

            // Your other methods...
        }
java download weblogic12c
1个回答
0
投票

通过添加以下行解决了:

response.setCharacterEncoding(“ISO-8859-1”)

© www.soinside.com 2019 - 2024. All rights reserved.