FTP下载文件失真问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Maskkiss/article/details/80348351

一、前言

    业务需要在特定的场景下给特定的用户发送带有图片压缩包的邮件。一开始我们使用的是普通的FTP下载方法,后来发现图片有失真问题,于是重新写了一种FTP的下载图片方法

二、代码逻辑

    public static boolean downloadImage(String hostname, int port, String username, String password, String pathname, String filename, String localFileName, String localpath){
        
    boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        try {
            //连接FTP服务器
            ftpClient.connect(hostname, port);
            //登录FTP服务器
            ftpClient.login(username, password);
            //设置文件类型
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //设置linux ftp服务器
            FTPClientConfig conf = new FTPClientConfig( FTPClientConfig.SYST_UNIX);
            ftpClient.configure(conf);
            
            //验证FTP服务器是否登录成功
            int replyCode = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(replyCode)){
            System.out.println("登录失败");
                return flag;
            }
            
            //设置访问被动模式
            ftpClient.setRemoteVerificationEnabled(false);
            ftpClient.enterLocalPassiveMode();
            
            
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            
            OutputStream os = new FileOutputStream(localpath + "/" + localFileName);
            
            flag = ftpClient.retrieveFile(filename, os);
            
            os.close();
            ftpClient.logout();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try {
                    ftpClient.logout();
                } catch (IOException e) {
                 
                }
            }
        }
        return flag;
    }

猜你喜欢

转载自blog.csdn.net/Maskkiss/article/details/80348351