SFTPUtil工具类spring boot

**

SFTPUtil工具类spring boot

**


import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

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

/**
 * 提供SFTP处理文件服务
 *
 * @author krm-hehongtao
 * @date 2016-02-29
 */
@Component
@ConfigurationProperties("sftp")
public class SFTPUtil {
    public SFTPUtil() {

    }

    private transient Logger log = LoggerFactory.getLogger(this.getClass());
    private JSch jSch;
    private ChannelSftp sftp; // sftp主服务
    private Channel channel;
    private Session session;

    private String hostName;// 远程服务器地址
    private int port; // 端口
    private String userName;// 用户名
    private String password;// 密码
    private String privateKey;//私钥

    /**
     * 构造基于密码认证的sftp对象
     *
     * @param hostName
     * @param port
     * @param userName
     * @param password
     */
    public SFTPUtil(String hostName, int port, String userName, String password) {
        this.hostName = hostName;
        this.port = port;
        this.userName = userName;
        this.password = password;
    }

    public SFTPUtil(String userName, String hostName, int port, String privateKey) {
        this.userName = userName;
        this.hostName = hostName;
        this.port = port;
        this.privateKey = privateKey;
    }

    /**
     * 连接登陆远程服务器
     *
     * @return
     */
    public boolean connect() throws Exception {
        try {
            jSch = new JSch();

            if (privateKey != null) {
                jSch.addIdentity(privateKey);// 设置私钥
                log.info("sftp connect,path of private key file:{}", privateKey);
            }
            log.info("sftp connect by host:{} username:{}", hostName, userName);

            session = jSch.getSession(userName, hostName, port);
            log.info("Session is build");
            if (password != null) {
                session.setPassword(password);
            }

            session.setConfig(this.getSshConfig());
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();
            log.info("Session is connected");

            sftp = (ChannelSftp) channel;
            log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", hostName, port));
            log.info("登陆成功:" + sftp.getServerVersion());

        } catch (JSchException e) {
            log.info("SSH方式连接FTP服务器时有JSchException异常!");
            log.info(e.getMessage());
            throw e;
        }
        return true;
    }

    /**
     * 关闭连接
     *
     * @throws Exception
     */
    private void disconnect() throws Exception {
        try {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                    log.info("sftp is closed already");
                }
            }
            if (channel != null) {
                if (channel.isConnected()) {
                    channel.disconnect();
                    log.info("sftp is closed already");
                }
            }
            if (session != null) {
                if (session.isConnected()) {
                    session.disconnect();
                    log.info("sshSession is closed already");
                }
            }
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取服务配置
     *
     * @return
     */
    private Properties getSshConfig() throws Exception {
        Properties sshConfig = null;
        try {
            sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");

        } catch (Exception e) {
            throw e;
        }
        return sshConfig;
    }

    /**
     * 下载远程sftp服务器文件
     *
     * @param remotePath
     * @param remoteFilename
     * @param localFilename
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFilename, String localFilename)
            throws SftpException, IOException, Exception {
        FileOutputStream output = null;
        boolean success = false;
        try {
            if (null != remotePath && remotePath.trim() != "") {
                sftp.cd(remotePath);
            }

            File localFile = new File(localFilename);
            // 有文件和下载文件重名
            if (localFile.exists()) {
                log.info("文件: " + localFilename + " 已经存在!");
                return success;
            }
            output = new FileOutputStream(localFile);
            sftp.get(remoteFilename, output);
            success = true;
            System.out.println("成功接收文件,本地路径:" + localFilename);
        } catch (SftpException e) {
            log.info("接收文件时有SftpException异常!");
            log.info(e.getMessage());
            return success;
        } catch (IOException e) {
            log.info("接收文件时有I/O异常!");
            log.info(e.getMessage());
            return success;
        } finally {
            try {
                if (null != output) {
                    output.close();
                }
                // 关闭连接
                disconnect();
            } catch (IOException e) {
                log.info("关闭文件时出错!");
                log.info(e.getMessage());
            }
        }
        return success;
    }

    /**
     * 上传文件至远程sftp服务器
     *
     * @param remotePath
     * @param remoteFilename
     * @param localFileName
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFilename, String localFileName)
            throws SftpException, Exception {
        boolean success = false;
            FileInputStream fis = null;
        try {
            // 更改服务器目录
            if (null != remotePath && remotePath.trim() != "") {
                sftp.cd(remotePath);
            }
            File localFile = new File(localFileName);
            fis = new FileInputStream(localFile);
            // 发送文件
            sftp.put(fis, remoteFilename);
            success = true;
            System.out.println("成功发送文件,本地路径:" + localFileName);
        } catch (SftpException e) {
            log.info("发送文件时有SftpException异常!");
            e.printStackTrace();
            log.info(e.getMessage());
            throw e;
        } catch (Exception e) {
            log.info("发送文件时有异常!");
            log.info(e.getMessage());
            throw e;
        } finally {
            try {
                if (null != fis) {
                    fis.close();
                }
                // 关闭连接
                disconnect();
            } catch (IOException e) {
                log.info("关闭文件时出错!");
                log.info(e.getMessage());
            }
        }
        return success;
    }

    /**
     * 上传文件至远程sftp服务器
     *
     * @param remotePath
     * @param remoteFilename
     * @param input
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFilename, InputStream input)
            throws SftpException, Exception {
        boolean success = false;
        try {
            // 更改服务器目录
            if (null != remotePath && remotePath.trim() != "") {
                sftp.cd(remotePath);
            }

            // 发送文件
            sftp.put(input, remoteFilename);
            success = true;
        } catch (SftpException e) {
            log.info("发送文件时有SftpException异常!");
            e.printStackTrace();
            log.info(e.getMessage());
            throw e;
        } catch (Exception e) {
            log.info("发送文件时有异常!");
            log.info(e.getMessage());
            throw e;
        } finally {
            try {
                if (null != input) {
                    input.close();
                }
                // 关闭连接
                disconnect();
            } catch (IOException e) {
                log.info("关闭文件时出错!");
                log.info(e.getMessage());
            }

        }
        return success;
    }

    /**
     * 删除远程文件
     *
     * @param remotePath
     * @param remoteFilename
     * @return
     * @throws Exception
     */
    public boolean deleteFile(String remotePath, String remoteFilename) throws Exception {
        boolean success = false;
        try {
            // 更改服务器目录
            if (null != remotePath && remotePath.trim() != "") {
                sftp.cd(remotePath);
            }

            // 删除文件
            sftp.rm(remoteFilename);
            log.info("删除远程文件" + remoteFilename + "成功!");
            success = true;
        } catch (SftpException e) {
            log.info("删除文件时有SftpException异常!");
            e.printStackTrace();
            log.info(e.getMessage());
            return success;
        } catch (Exception e) {
            log.info("删除文件时有异常!");
            log.info(e.getMessage());
            return success;
        } finally {
            // 关闭连接
            disconnect();
        }
        return success;
    }

    /**
     * 遍历远程文件
     *
     * @param remotePath
     * @return
     * @throws Exception
     */
    public List<String> listFiles(String remotePath) throws SftpException {
        List<String> ftpFileNameList = new ArrayList<String>();
        Vector<LsEntry> sftpFile = sftp.ls(remotePath);
        LsEntry isEntity = null;
        String fileName = null;
        Iterator<LsEntry> sftpFileNames = sftpFile.iterator();
        while (sftpFileNames.hasNext()) {
            isEntity = (LsEntry) sftpFileNames.next();
            fileName = isEntity.getFilename();
            System.out.println(fileName);
            ftpFileNameList.add(fileName);
        }
        return ftpFileNameList;
    }

    /**
     * 判断路径是否存在
     *
     * @param remotePath
     * @return
     * @throws SftpException
     */
    public boolean isExist(String remotePath) throws SftpException {
        boolean flag = false;
        try {
            sftp.cd(remotePath);
            System.out.println("存在路径:" + remotePath);
            flag = true;
        } catch (SftpException sException) {

        } catch (Exception Exception) {
        }
        return flag;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        try {
            SFTPUtil sftp = new SFTPUtil("服务器ip", 端口, "服务器名字", "密码");
            System.out.println(new StringBuffer().append(" 服务器地址: ")
                    .append(sftp.getHostName()).append(" 端口:").append(sftp.getPort())
                    .append("用户名:").append(sftp.getUserName()).append("密码:")
                    .append(sftp.getPassword().toString()));
            sftp.connect();
            if (sftp.isExist("/root/nginx/pic")) {
                sftp.listFiles("/root/nginx/pic");
                sftp.uploadFile("/root/nginx/pic", "40bd0804-d74d-42a6-a741-a3ae3c387427.jpg",
                        "D:\\nginx-1.17.1\\html\\upload\\40bd0804-d74d-42a6-a741-a3ae3c387427.jpg");
                // sftp.uploadFile("\\", "test.txt", "D:\\work\\readMe.txt");
                // sftp.deleteFile("\\", "test.txt");
            }
        } catch (Exception e) {
            System.out.println("异常信息:" + e.getMessage());
        }
    }
}

使用案例
1【在启动类注入bean
在项目启动类加上这个
2【controller代码

@PostMapping("uploads")
    public Result uploads(MultipartFile pic) throws Exception {
        String filename = pic.getOriginalFilename();//获取头像图片名字
        String substring = filename.substring(filename.lastIndexOf("."));//获取文件后缀
        filename = UUID.randomUUID().toString() + substring;//通过uuid重组文件名
        InputStream inputStream = pic.getInputStream();//转换成流
        String remotePath = "/root/nginx/pic/";//服务器路径
        String url = "http://81.69.56.151:/pic/" + filename;//返回数据库路径
        sftpUtil.connect();//开启sftp
        sftpUtil.uploadFile(remotePath,filename,inputStream);//调用方法上传文件
//         写出图片
//        pic.transferTo(new File(dirPath));
        User user = userService.findById(LoginUtil.getId());
        user.setPic(url);//保存回数据库
        userService.save(user);
        redisTemplate.opsForValue().set("loginUser:" + user.getId(), user, 30, TimeUnit.MINUTES);
        return new Result(StatusCode.OK, true, "上传成功",url);

3【前端vue.js代码

 uploads(event) {
            let formData = new FormData();
            formData.append("pic", document.getElementById("picFile").files[0]);
            axios.post("user/uploads", formData, {contentType: 'multipart/form-data'}).then(response => {
                if (response.data.flag) {
                    this.user.pic = response.data.data;
                    localStorage.setItem("loginUser", JSON.stringify(this.user));
                }
                layer.msg(response.data.message)

            });
            event.target.value = '';
        },

4【html代码

<input type="file" id="picFile" @change="uploads($event)" class="hidden uploadImg">

5【效果图
上传前
选择图片
后台断点详情
成果图

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值