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;
    }
}
最近下载更多
stdtta  LV8 2022年6月28日
wang512237140  LV20 2021年12月21日
icesolitude  LV8 2021年7月6日
谎言diw  LV2 2021年5月22日
程序世界  LV5 2021年4月26日
水光浮藻  LV6 2021年3月16日
15827485252  LV19 2020年8月27日
zhurm959  LV3 2020年7月6日
LKBBDD  LV7 2020年5月16日
chamberlens  LV2 2020年5月6日
最近浏览更多
WBelong  LV7 4月2日
fff2003  LV6 2023年11月17日
漫步的海星  LV4 2023年9月21日
13940065360 2023年8月17日
暂无贡献等级
liuxingyu5214  LV1 2023年6月24日
skook7  LV2 2023年6月1日
CL200228  LV4 2023年4月29日
微信网友_6401519212040192  LV1 2023年4月25日
lyws1986  LV17 2023年3月13日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友