java sftp上传图片到本地服务器

      之前公司有地区的项目用的ftp上传图片,一直没问题,

      有一天有一个新的客户提供的服务器用ftp上传,怎么上传都不行,看日志是能连接成功,但是传输不了内容,连接过多情况下,还把服务卡死了。

      后来经过一顿分析,终于找到原因防火墙开启了,但是我们有的客户防火墙是开启的用ftp也没事(不过多久结),然后决定用sftp进行上传,sftp只需要一个端口就行。后来发现改成sftp,相安无事。

   一下是相关代码:

/**
     * 连接登陆远程服务器
     *
     * @return
     */
    public static boolean connect(Sftp ftp) throws Exception {
        try {
            jSch = new JSch();
            session = jSch.getSession(ftp.getFtpName(), ftp.getFtpIp(), Integer.parseInt(ftp.getFtpPort()));
            session.setPassword(ftp.getFtpPwd());
            session.setConfig("StrictHostKeyChecking", "no");
            // session.setConfig(getSshConfig());
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            log.info("登陆成功:{}",sftp.getServerVersion());
        } catch (JSchException e) {
            log.error("SSH方式连接FTP服务器时有JSchException异常!{}",e.getMessage());
            throw e;
        }
        return true;
    }

 /**
     * 关闭连接
     *
     * @throws Exception
     */
    private static void disconnect() throws Exception {
        try {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
            if (channel.isConnected()) {
                channel.disconnect();
            }
            if (session.isConnected()) {
                session.disconnect();
            }
            log.info("关闭");
        } catch (Exception e) {
            throw e;
        }
    }

/**
     * 312      * 判断路径是否存在
     * 313      *
     * 314      * @param remotePath
     * 315      * @return
     * 316      * @throws SftpException
     * 317
     */
    public static boolean isExist(String remotePath) throws SftpException {
        boolean flag = false;
        try {
            sftp.cd(remotePath);
            log.info("存在路径:{}", remotePath);
            flag = true;
        } catch (SftpException sException) {
            log.info("不存在路径:{}", remotePath);
        } catch (Exception Exception) {
            log.info("不存在路径:{}", remotePath);
        }
        return flag;
    }

    /**
     * 创建目录
     *
     * @param createpath
     * @param sftp
     */
    public static void createDir(String createpath, ChannelSftp sftp) {
        try {
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                // 建立目录
                sftp.mkdir(filePath.toString());
                // 进入并设置为当前目录
                sftp.cd(filePath.toString());
            }
            log.info("创建路径:{}", createpath);
        } catch (SftpException e) {
            log.error("创建路径错误:{}", e.getMessage());
        }
    }

public static Boolean upload(File file,Sftp ftp,String url) throws Exception {
        connect(ftp);
        boolean success = false;
        FileInputStream fis = null;
        try {
            boolean flag = isExist(url);
            if (!flag) {
                createDir(url, sftp);
            }
            // 更改服务器目录
            if (null !=  url &&  url.trim() != "") {
                sftp.cd( url);
            }
            fis = new FileInputStream(file);
            // 发送文件
            sftp.put(fis, file.getName());
            success = true;
            log.info("成功发送文件,本地路径:" + file.getName());
        } catch (SftpException e) {
            log.error("发送文件时有SftpException异常!{}", e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            log.error("发送文件时有异常!{}", e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (null != fis) {
                    fis.close();
                }
                disconnect();
            } catch (IOException e) {
                log.error("关闭文件时出错!{}",e.getMessage());
            }
        }
        return success;
    }

    public static void main(String[] args) throws Exception {
        File localFile = new File("D:\\Face\\1.jpg");
        Ftp ftp = new Ftp();
        ftp.setFtpName("");
        ftp.setFtpPwd("");
        ftp.setFtpPort("");
        ftp.setFtpIp("");
        uploadPhoto(localFile,ftp);
      
    }

需要引入jar包

<dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.49</version>
        </dependency>

大功告成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬砖-无恙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值