java实现ftp上传文件(附linux安装vsftpd)

内容分享2个月前发布
0 0 0

1.进入服务器终端,通过 rpm -qa|grep vsftpd 查看ftp是否安装。已安装如下图:

java实现ftp上传文件(附linux安装vsftpd)

2.未安装
安装,并设置开机启动
yum -y install vsftpd
chkconfig vsftpd on

管理vsftpd相关命令:
启动vsftpd: service vsftpd start
停止vsftpd: service vsftpd stop
重启vsftpd: service vsftpd restart

配置防火墙
打开/etc/sysconfig/iptables文件
vi /etc/sysconfig/iptables

在REJECT行之前添加如下代码
-A RH-Firewall-1-INPUT -m state –state NEW -m tcp -p tcp –dport 21 -j ACCEPT

保存和关闭文件,重启防火墙
service iptables restart
安装完成后来,可以用以下代码来上传文件(有关vsftpd黑名单、和临时用户后来会详细说明)

import lombok.Data;
import java.io.InputStream;
@Data
public class UpOrDownloadFile {

    //服务器ip
    private String ftpHost;
    //服务器端口号
    private int ftpPort;
    //用户名
    private String ftpUserName;
    //密码
    private String ftpPassword;
    //基础路径
    private String basePath;
    //文件路径
    private String filePath;
    //文件名
    private String fileName;
    //io流
    private InputStream input;
}


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
import java.net.SocketException;

/**
 * ftp 工具类
 */
@Slf4j
public class FtpUtil {

    private static FTPClient getFTPClient(String host, int port, String userName, String password) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            //设置被动模式 设置被动模式必定要在ftpClient.connect(host, port);之前
            ftpClient.enterLocalPassiveMode();
            ftpClient.connect(host, port);
            ftpClient.login(userName, password);
            boolean flag = FTPReply.isPositiveCompletion(ftpClient.getReplyCode());
            log.info(" flag:{}", flag);
            if (!flag) {
                log.info(" 未连接到FTP ,用户名或密码错误:{}");
                ftpClient.disconnect();
            } else {
                log.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            log.info("FTP的IP地址错误,请正确配置:{}", e.getMessage());
        } catch (IOException e) {
            log.error("FTP 端口错误,请检查配置:{}", e.getMessage());
        }
        return ftpClient;
    }

    /**
     * 上传文件
     * @param upOrDownloadFile
     * @return
     */
    public static boolean uploadFile(UpOrDownloadFile upOrDownloadFile  )  {
        boolean result = false;
        FTPClient ftpClient = null;
        try {
            ftpClient = getFTPClient(upOrDownloadFile.getFtpHost(), upOrDownloadFile.getFtpPort(), upOrDownloadFile.getFtpUserName(), upOrDownloadFile.getFtpPassword());
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return result;
            }
            //切换到上传目录
            boolean isChangeSuccess = ftpClient.changeWorkingDirectory(upOrDownloadFile.getBasePath() + upOrDownloadFile.getFilePath());
            //如果切换失败则创建改目录再切换
            if (!isChangeSuccess) {
                // 如果目录不存在创建目录
                String[] dirs = upOrDownloadFile.getFilePath().split("/");
                String tempPath = upOrDownloadFile.getBasePath();
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir))
                        continue;
                    tempPath += "/" + dir;
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        if (!ftpClient.makeDirectory(tempPath)) {
                            log.info("目录创建失败:{}",tempPath);
                            return result;
                        } else {
                            ftpClient.changeWorkingDirectory(tempPath);
                        }
                    }
                }
                ftpClient.changeWorkingDirectory(upOrDownloadFile.getBasePath() + upOrDownloadFile.getFilePath());
            }
            //设置缓冲大小,编码格式,文件类型
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //开始上传
            log.info("开始上传文件:{}", upOrDownloadFile.getFileName());
            result = ftpClient.storeFile(upOrDownloadFile.getFileName(), upOrDownloadFile.getInput());
            log.info("文件:{},上传:{}", upOrDownloadFile.getFileName(), result);
            return result;
        } catch (IOException e) {
            log.error(" 文件上传失败:{}", e.getMessage());
        } finally {
            try {
                //关闭输入流和ftp连接
                upOrDownloadFile.getInput().close();
                ftpClient.logout();
            } catch (IOException e) {
                log.error(" 输入流关闭失败:{}", e.getMessage());
            }

        }
        return result;

    }
}

© 版权声明

相关文章

暂无评论

none
暂无评论...