Binary file getting corrupted when trying to download using Struts 6.3.0.2 with Java

60 views Asked by At

When I am trying to download the pdf and doc-x file from my app after upgrading from struts2 to struts 6.3.0.2, the file is getting corrupted. I am not able to open the pdf file when I have downloaded from the app after I uploaded to the app. For the doc-x file it is showing System is unable to process with your request which is the custom error from the errors file. On the console it shows that the file has been downloaded successfully but still the doc-x file cannot be opened.

This is my original code before the upgrade


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

This is my edited code but I am still not able to open the downloaded pdf and doc-x file

    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...
        }
1

There are 1 answers

0
Mahabir Gupta On

It was resolved by adding the line:

response.setCharacterEncoding("ISO-8859-1")