Java用SFTP实现上传下载功能

wylc123 1年前 ⋅ 472 阅读

引入maven配置:

com.alibaba.citrus.tool
antx-autoconfig
1.2
        

工具类(支持多级目录创建):

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

import com.jcraft.jsch.*;

/**
 * SFTP工具类
 */
public class SFTPUtils {
    static Session sshSession = null;


    public static void main(String[] args) {
        ChannelSftp ftp = getConnectIP("192.168.100.47", "22", "sftpuser", "sftppass");
        upload("/home/sftpuser/sftpdata/235", "/Users/XXX/批量任务.txt", ftp);
        
    }

    /**
     * 获取ChannelSftp
     *
     * @param host            主机
     * @param sOnlineSftpPort 端口
     * @param username        用户名
     * @param password        密码
     * @return
     */
    public static ChannelSftp getConnectIP(String host, String sOnlineSftpPort, String username, String password) {
        int port = 0;
        if (!("".equals(sOnlineSftpPort)) && null != sOnlineSftpPort) {
            port = Integer.parseInt(sOnlineSftpPort);
        }
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sftp;
    }

    /**
     * 上传 gst
     *
     * @param directory  sftp 服务器目录
     * @param uploadFile 上传文件路径
     * @param sftp
     */
    public static void upload(String directory, String uploadFile, ChannelSftp sftp) {
        try {
            createDir(directory,sftp);
            sftp.cd(directory);
            File file = new File(uploadFile);
            sftp.put(new FileInputStream(file), file.getName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
    }

    /**
     * 流写入到文件
     *
     * @param directory
     * @param inputStream
     * @param sftp
     * @param filename
     */
    public static void upload(String directory, InputStream inputStream, ChannelSftp sftp, String filename) {
        try {
            createDir(directory,sftp);
            sftp.cd(directory);
            sftp.put(inputStream, filename);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
    }

    /**
     * 下载
     *
     * @param directory    sftp服务器目录
     * @param downloadFile 目录下的文件名称
     * @param saveFile     本地保存文件路径
     * @param sftp
     */
    public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
    }

    /**
     * 创建目录,支持多级创建
     *
     * @param fullPathName 全路径,如/x/y/z
     * @throws SftpException
     */
    public static void createDir(String fullPathName, ChannelSftp sftp) throws SftpException {
        if (fullPathName.startsWith("/")) {
            fullPathName = fullPathName.substring(1);
        }
        if (fullPathName.endsWith("/")) {
            fullPathName = fullPathName.substring(0, fullPathName.lastIndexOf("/"));
        }
        fullPathName.replace("//", "/");
        if (!isDir(fullPathName, sftp)) {
            String[] path = fullPathName.split("/");
            String base = "/";
            for (int i = 0; i < path.length - 1; i++) {
                base += path[i] + "/";
                createDir(base, path[i + 1], sftp);
            }
        }
    }

    /**
     * 是否是目录
     *
     * @param dir
     * @return
     */
    public static boolean isDir(String dir, ChannelSftp sftp) {
        try {
            sftp.cd(dir);
            sftp.cd("..");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 创建目录
     *
     * @param parent
     * @param dir
     * @throws SftpException
     */
    public static void createDir(String parent, String dir, ChannelSftp sftp) throws SftpException {
        if (!isDir(parent, sftp)) {
            sftp.mkdir(parent);
        }
        if (!isDir(parent + dir, sftp)){
            sftp.mkdir(parent + dir);
        }
    }

    /**
     * 删除
     *
     * @param directory
     * @param deleteFile
     * @param sftp
     */
    public static void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
    }

}

通过接口接收前端页面上传的文件再存到sftp服务器:

 @PostMapping("/test")
    public @ResponseBody
    TaskResponse postTaskResultByAncheId(String path,String filename, MultipartFile file) {
        ChannelSftp ftp = getConnectIP("192.168.100.47", "22", "sftpuser", "sftppass");
        try {
            SFTPUtils.upload(path, file.getInputStream(), ftp,filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // download("
        return new TaskResponse();
    }

postman测试接口:

更多内容请访问:IT源点

全部评论: 0

    我有话说: