SFTP文件上传到文件服务器

配置文件

#图片访问路径   nginx 静态资源配置
upload-server=http://xx.xx.xx.xx/images/

#图片服务器存放地址
upload-path=/usr/local/static/images/

# 图片服务器  sftp IP
sftp-host=xx.xx.xx.xx

# 图片服务器 sftp 端口
sftp-port=22

# 公司的 sFTP服务器 用户名
sftp-username=root

# 公司的 sFTP服务器 密码
sftp-password=xxxxxxxxxx

JAVA 工具类

package com.ningpai.third.common;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

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


/**
 * ftp 工具类
 *
 * @author MENG
 * @version 2018/4/18
 * @see
 */
public class SftpUtils
{
    private static Logger logger = LoggerFactory.getLogger(SftpUtils.class);

    private static String encoding = "UTF-8";

    private ChannelSftp sftp;

    private Session session;

    /** SFTP 登录用户名*/
    private String username;

    /** SFTP 登录密码*/
    private String password;

    /** SFTP 服务器地址IP地址*/
    private String host;

    /** SFTP 端口*/
    private int port;


    public SftpUtils(String username, String password , String host, int port)
    {
        this.port = port;

        this.host = host;

        this.password = password;

        this.username = username;
    }

    /**
     *
     * 连接Ftp服务器
     *
     * @return
     */
    public void connectSFtp()
    {
        try
        {
            JSch jsch = new JSch();

            Session session = jsch.getSession(username, host, port);

            Properties config = new Properties();

            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);

            session.setPassword(password);

            session.connect();

            Channel channel = session.openChannel("sftp");

            channel.connect();

            sftp = (ChannelSftp) channel;
        }
        catch (JSchException e)
        {
            logger.error("SFTP 服务器连接失败!!! ip:{},port:{},username:{},password:{}",new String[]{host,port+"",username,password});

            logger.error("",e);
        }

    }

    /**
     * 关闭Ftp连接
     *
     * @throws IOException
     */
    public void closeFptConnect()
    {
        if (sftp != null)
        {
            if (sftp.isConnected())
            {
                sftp.disconnect();

                logger.info("sftp 已经关闭");
            }
        }
        if (session != null)
        {
            if (session.isConnected())
            {
                session.disconnect();

                logger.info("sshSession 已经关闭");
            }
        }
    }
    /**
     * 将文件上传 spring
     */
    public void uploadMultipartFile(MultipartFile file, String newFileName, String uploadPath)
        throws SftpException, IOException
    {
        InputStream inputStream = null;

        inputStream = file.getInputStream();

        createDir(uploadPath);

        sftp.put(inputStream, newFileName);

        inputStream.close();
    }


    /**
     * 将本地文件上传
     */
    public  void uploadFile(File file, String newFileName, String uploadPath)
        throws IOException, SftpException
    {
        InputStream inputStream = null;

        inputStream = new FileInputStream(file);

        createDir(uploadPath);

        sftp.put(inputStream, newFileName);

        inputStream.close();
    }

    /**
     * 连接上传图片服务器的ftp
     */
    public static SftpUtils connectUploadImageServer()
    {
        Properties properties = PropertiesUtils.readUploadProperties();

        SftpUtils sftpUtils = new SftpUtils(properties.getProperty("sftp-username"),properties.getProperty("sftp-password"),properties.getProperty("sftp-host"),Integer.valueOf(properties.getProperty("sftp-port")));

        sftpUtils.connectSFtp();

        return sftpUtils;
    }

    /**
     * 创建循环创建文件目录
     *
     * @param uploadPath 上传目录
     * @throws SftpException
     */
    public void createDir(String uploadPath)
        throws SftpException
    {
        if(!isExistDir(uploadPath))
        {
            String pathArry[] = uploadPath.split("/");

            StringBuffer filePath = new StringBuffer("/");

            for (String path : pathArry)
            {
                if (path.equals(""))
                {
                    continue;
                }

                filePath.append(path + "/");

                if (isExistDir(filePath.toString()))
                {
                    sftp.cd(filePath.toString());
                }
                else
                {
                    // 建立目录
                    sftp.mkdir(filePath.toString());

                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }
            }
        }
    }

    /**
     * 目录是否存在
     * @param path
     * @return
     */
    private boolean isExistDir(String path)
    {
        try
        {
            sftp.cd(path);

            return true;
        }
        catch (SftpException e)
        {
            return false;
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,606评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,087评论 6 342
  • (稻盛哲学学习会)打卡第93天 姓名:李晨珂 部门:分水碶 组别:待定 【知~学习】 诵读《京瓷哲学》第一章 度过...
    李晨珂分水碶阅读 1,313评论 0 0
  • 儿子开始对节日有概念了,早早就提出了六一的三个愿望:一是玩冒险岛(类似儿童拓展训练),二是吃个蛋糕(好久没吃了呀)...
    驴驴妈阅读 3,262评论 0 0
  • 刚刚在微信上与一位病友聊天,刚好她最近这两天身体不适,发烧三十九度五,昨晚开始到我们聊天时还没有退烧,虽然...
    笑笑狗尾草阅读 1,313评论 0 0