How can i get pdf files from FTP server as base64 encoding format on Java spring mvc project?

Tags: , , ,



I’m trying getting files from FTP server on Java spring mvc project. I’m study on windows but my tomcat server is in linux machine. Following code returns base64 encoding files and created base64 url for front end side and this files temporarily held. This code works fine windows but works bad on linux machine. Getting pdf files are issueless in windows, corrupted in linux machine. Works differently according to file size.

This result in linux machine, this file is issueless in folder of FTP. enter image description here

This result on windows machine

enter image description here

Can the problem be caused by base64 encoding?

public List<String> getMultipleBase64PDF(String workingDir) {
    List<String> fileList = new ArrayList<>();
    try {
        FTPFile[] files = client.listFiles(workingDir);
        for (FTPFile file : files) {
            if (file.getName().endsWith(".pdf")) {
                fileNames.add(file.getName());
            }
        }
        if (fileNames.size() > 0) {
            for (String filename : fileNames) {
                String encodedFile = "";
                InputStream is = client.retrieveFileStream( workingDir);
                File file = File.createTempFile("tmp", null);
                FileUtils.copyInputStreamToFile(is, file); 
                byte[] bytes = new byte[(int) file.length()];
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                bis.read(bytes, 0, (int) file.length());
                bis.close();
                encodedFile += new String(Base64.getEncoder().withoutPadding().encode(bytes), "UTF-8");
                fileList.add(encodedFile);
                file.delete();
                client.completePendingCommand();
            }
        }
        disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileList;
}

Answer

FTPClient is set to ASCII by default. While configuring FTPClient bean, try switching your client from using ASCII to binary, like so:

client.setFileType(FTP.BINARY_FILE_TYPE);

Here’s the original answer for the similair problem



Source: stackoverflow