package com.test.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Service
@PropertySource("classpath:ftp/ftp.properties")
public class FTPService {

    @Value("${ftp.ip}")
    private String FTP_IP;

    @Value("${ftp.port}")
    private int FTP_PORT;

    @Value("${ftp.user}")
    private String FTP_USER;

    @Value("${ftp.password}")
    private String FTP_PASSWORD;

    private FTPClient ftpClient = new FTPClient();

    public boolean connectFTP () {
        boolean flag = false;
        try {
            ftpClient.connect(FTP_IP, FTP_PORT);//连接FTP服务器
            ftpClient.login(FTP_USER, FTP_PASSWORD);//登录FTP服务器
            int reply = ftpClient.getReplyCode();
            /**
             * FTP服务器: 220 (vsFTPd 2.0.1)                                          |说明:链接成功
             * FTP客户端: USER useway                                                 |说明:输入用户名
             * FTP服务器: 331 Please specify the password.                            |说明:请输入密码
             * FTP客户端: PASS !@#$%abce                                              |说明:输入密码
             * FTP服务器: 230 Login successful.                                       |说明:登录成功
             * FTP客户端: CWD /home/useway                                            |说明:切换目录
             * FTP服务器: 250 Directory successfully changed.                         |说明:目录切换成功
             * FTP客户端: EPSV ALL                                                    |说明:为EPSV被动链接方式
             * FTP服务器: 200 EPSV ALL ok.                                            |说明:OK
             * FTP客户端: EPSV                                                        |说明:链接
             * FTP服务器: 229 Entering Extended Passive Mode (|||62501|)              |说明:被动链接端口为62501
             * FTP客户端: LIST                                                        |说明:执行LIST显示文件列表
             * FTP服务器: 150 Here comes the directory listing.                       |说明:列表从62501端口被发送
             * FTP服务器: 226 Directory send OK.                                      |说明:发送完成
             * FTP客户端: QUIT                                                        |说明:退出FTP
             * FTP服务器: 221 Goodbye.                                                |说明:再见
             */
            System.out.println("连接FTP服务器返回的代码代号:"+reply);
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
            } else {
                flag = true;
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * FTP创建多级目录文件夹,比如/a/b/c/d, 不允许支持中文目录
     * @param dirName 文件夹目录
     * @return
     */
    public boolean createFTPDir (String dirName) {
        boolean flag = false;
        try {
            if (!StringUtils.isBlank(dirName)) {
                boolean connectFlag = connectFTP();
                if (connectFlag) {
                    String[] dirNames = dirName.split("/");
                    for (int i=0; i<dirNames.length; i++) {
                        if (StringUtils.isNotBlank(dirNames[i])) {
                            System.out.println("创建FTP服务器上文件夹名称:"+dirNames[i]);
                            flag = ftpClient.makeDirectory(dirNames[i]);
                            ftpClient.changeWorkingDirectory(dirNames[i]);//切换到生成的目录进行创建层级目录
                        }
                    }
                }
            }
        } catch (Exception e) {
            flag = false;
            System.out.println("error创建FTP服务器上文件夹"+dirName+"失败!");
            e.printStackTrace();
        } finally {
            if (ftpClient!=null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * FTP上传
     * @param remotePath FTP服务器上的完整文件路径,比如/a/b/c/d/1.png
     * @param in 需要上传到FTP的文件流
     * @return
     */
    public boolean upload (String remotePath, InputStream in) {
        boolean flag = false;
        try {
            if (!StringUtils.isBlank(remotePath) && in!=null && in.available()>0) {
                boolean connectFlag = connectFTP();
                if (connectFlag) {
                    ftpClient.setBufferSize(1024);
                    ftpClient.setControlEncoding("UTF-8");
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    ftpClient.enterLocalPassiveMode();
                    flag = ftpClient.storeFile(remotePath, in);
                }
            }
        } catch (Exception e) {
            flag = false;
            System.out.println("error上传文件至FTP服务器上远程路径"+remotePath+"失败!");
            e.printStackTrace();
        } finally {
            if (ftpClient!=null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * FTP上传文件
     * @param remotePath FTP服务器上的完整文件路径,比如/a/b/c/d/1.png
     * @return
     */
    public OutputStream upload (String remotePath) {
        OutputStream out = null;
        try {
            if (!StringUtils.isBlank(remotePath)) {
                boolean connectFlag = connectFTP();
                if (connectFlag) {
                    ftpClient.setBufferSize(1024);
                    ftpClient.setControlEncoding("UTF-8");
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    ftpClient.enterLocalPassiveMode();
                    out = ftpClient.storeFileStream(remotePath);
                }
            }
        } catch (Exception e) {
            System.out.println("error上传文件至FTP服务器上远程路径"+remotePath+"失败!");
            e.printStackTrace();
        } finally {
            if (ftpClient!=null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return out;
    }

    /**
     * FTP下载文件
     * @param remotePath FTP服务器上的完整文件路径,比如/a/b/c/d/1.png
     * @param out
     * @return
     */
    public boolean download (String remotePath, OutputStream out) {
        boolean flag = false;
        try {
            if (!StringUtils.isBlank(remotePath)) {
                boolean connectFlag = connectFTP();
                if (connectFlag) {
                    ftpClient.setBufferSize(1024);
                    ftpClient.setControlEncoding("UTF-8");
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    ftpClient.enterLocalActiveMode();
                    flag = ftpClient.retrieveFile(remotePath, out);
                }
            }
        } catch (Exception e) {
            flag = false;
            System.out.println("error从FTP服务器上远程路径"+remotePath+"下载文件失败!");
            e.printStackTrace();
        } finally {
            if (ftpClient!=null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out!=null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * FTP下载文件
     * @param remotePath FTP服务器上的完整文件路径,比如/a/b/c/d/1.png
     * @return
     */
    public InputStream download(String remotePath) {
        InputStream in = null;
        try {
            if (!StringUtils.isBlank(remotePath)) {
                boolean connectFlag = connectFTP();
                if (connectFlag) {
                    ftpClient.setBufferSize(1024);
                    ftpClient.setControlEncoding("UTF-8");
                    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    ftpClient.enterLocalActiveMode();
                    in = ftpClient.retrieveFileStream(remotePath);
                }
            }
        } catch (Exception e) {
            System.out.println("error从FTP服务器上远程路径"+remotePath+"下载文件失败!");
            e.printStackTrace();
        } finally {
            if (ftpClient!=null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return in;
    }
}
最近下载更多
lcqlcl  LV11 2023年8月29日
lironggang  LV38 2023年3月31日
annazhang  LV29 2022年12月1日
zw050256  LV7 2022年9月30日
wuyu8995861  LV7 2022年7月26日
zxysss  LV3 2022年1月6日
cwx1234  LV11 2021年10月8日
123456nty  LV37 2021年9月18日
newhaijun  LV15 2021年8月23日
zy_286315  LV7 2021年8月4日
最近浏览更多
WBelong  LV7 2023年12月19日
lichengai  LV7 2023年11月27日
漫步的海星  LV4 2023年9月21日
lcqlcl  LV11 2023年8月29日
cwb6357123  LV6 2023年6月30日
CL200228  LV4 2023年4月29日
mzj695 2023年4月6日
暂无贡献等级
lironggang  LV38 2023年3月31日
清横白川玉  LV5 2023年1月3日
annazhang  LV29 2022年12月1日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友