Java将文件上传到ftp服务器(ChannelSftp)

一、添加maven依赖
<dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.7.2</version>
        </dependency>
1
2
3
4
5
二、主要代码块
package com.eurekaclient.utils;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Properties;

@Slf4j
public class FtpUtils {

    /**
     * ftp地址
     */
    private static final String ftpIp = "127.0.0.1";
    /**
     * ftp端口
     */
    private static final String ftpPort = "22";
    /**
     * ftp账户
     */
    private static final String ftpUserName = "admin";
    /**
     * ftp密码
     */
    private static final String ftpPassWord = "admin";
    /**
     * 超时时间
     */
    private static final String timeout = "6000";
    /**
     * sftp对象
     */
    private static ChannelSftp channelSftp = null;
    /**
     * 会话
     */
    private static Session session = null;

    /**
     * 通道
     */
    private static Channel channel = null;

    /**
     * 判断ftp是否已连接
     *
     * @return
     */
    public static boolean isOpen() {
        try {
            channelSftp = new ChannelSftp();
            channelSftp.getServerVersion();
            return true;
        } catch (Exception e) {
            log.error("{}", e.getMessage());
            return false;
        }

    }

    /**
     * ftp链接
     */
    public static void connectionFtp() {
        try {
            boolean open = isOpen();
            if (!open) {
                // 创建JSch对象
                JSch jsch = new JSch();
                // 通过 用户名,主机地址,端口 获取一个Session对象
                session = jsch.getSession(ftpUserName, ftpIp, Integer.parseInt(ftpPort));
                session.setPassword(ftpPassWord);

                // 为Session对象设置properties
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                // 设置超时时间
                session.setTimeout(Integer.parseInt(timeout));
                // 建立链接
                session.connect();
                // 打开SFTP通道
                channel = session.openChannel("sftp");
                // 建立SFTP通道的连接
                channel.connect();
                channelSftp = (ChannelSftp) channel;
            }
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
    }

    /**
     * @param uploadPath 上传文件地址
     * @param localPath  本地文件地址
     */
    public static void uploadImage(String uploadPath, String localPath) {
        FileInputStream io = null;
        try {
            log.info("上传图片starting");
            connectionFtp();
            if (null == channelSftp || channelSftp.isClosed()) {
                log.error("链接丢失");
            }
            if (isExistDir(uploadPath)) {
                channelSftp.cd(uploadPath);
            } else {
                createDir(uploadPath, channelSftp);
            }
            File file = new File(localPath);
            io = new FileInputStream(file);
            channelSftp.put(io, file.getName());
            log.info("上传图片ending");
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        } finally {
            if (null != io) {
                try {
                    io.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            disconnect();
        }

    }

    /**
     * @param downloadPath 下载文件地址
     * @param localPath    本地文件地址
     */
    public static void downLoad(String downloadPath, String localPath) {
        FileOutputStream out = null;
        try {
            log.info("下载图片starting");
            connectionFtp();
            if (null == channelSftp || channelSftp.isClosed()) {
                log.error("链接丢失");
            }
            String[] pathArry = downloadPath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (int i = 0; i < pathArry.length - 1; i++) {
                if ("".equals(pathArry[i])) {
                    continue;
                }
                filePath.append(pathArry[i]).append("/");
            }
            channelSftp.cd(filePath.toString());
            log.info("当前目录为:{}", channelSftp.pwd());
            //判断本地是否有目录
            File files = new File(localPath);
            if (!files.exists()) {
                boolean mkdirs = files.mkdirs();
                log.info("创建目录:{}", mkdirs);
            }
            // 可写
            if (!files.canWrite()) {
                if (!files.setWritable(true)) {
                    throw new FileNotFoundException();
                }
            }
            String fileName = pathArry[pathArry.length - 1];
            File file = new File(localPath + fileName);
            out = new FileOutputStream(file);
            channelSftp.get(downloadPath, out);

        } catch (Exception e) {
            log.error("{}", e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("{}", e.getMessage());
                }
            }
            disconnect();
        }
    }

    /**
     * 关闭ftp
     */
    public static void disconnect() {
        if (channelSftp.isConnected()) {
            session.disconnect();
            channelSftp.disconnect();
        }
    }

    /**
     * 判断目录是否存在并创建目录
     */
    public static boolean isExistDir(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpAttrS = channelSftp.lstat(directory);
            isDirExistFlag = true;
            return sftpAttrS.isDir();
        } catch (Exception e) {
            if ("no such file".equals(e.getMessage().toLowerCase())) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * @param createpath 文件目录地址
     */
    public static void createDir(String createpath, ChannelSftp sftp) throws Exception {
        try {
            String[] pathArry = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if ("".equals(path)) {
                    continue;
                }
                filePath.append(path).append("/");
                if (isExistDir(filePath.toString())) {
                    sftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }
            }
            channelSftp.cd(createpath);
        } catch (SftpException e) {
            log.error("创建目录失败,{}", e.getMessage());
        }
    }
}


三、测试类
package com.eurekaclient.controller;

import com.eurekaclient.utils.FtpUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FtpController {


    public static void main(String[] args) {
        try {
            FtpUtils.uploadImage("/vsftp/data/test/", "D:\\images\\063c6aa05dfa49acb705f928f5e5f3a8.jpg");
            FtpUtils.downLoad("/vsftp/data/test/063c6aa05dfa49acb705f928f5e5f3a8.jpg", "D:\\images\\");
        } catch (Exception e) {
            log.info("{}", e.getMessage());
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

————————————————
版权声明:本文为CSDN博主「微微~」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42906244/article/details/126406329

猜你喜欢

转载自blog.csdn.net/gb4215287/article/details/132266077
今日推荐