最近有个需求:前台传递文件(图片)到后台,需要将此上传到远程服务器上,再次记录下整个流程和涉及到的工具类

工具类:

package com.jsyd.ict.ictservicemanager.util.file;import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;import java.io.*;
import java.util.Properties;
import java.util.Vector;/**** SFTP工具类* @author wangyang* @version 1.0* @date 2021/3/18 17:12*/
public class SFtpUtil {private static final Log LOG = LogFactory.getLog(SFtpUtil.class);private ChannelSftp sftp;private Session session;/** FTP 登录用户名*/private String username;/** FTP 登录密码*/private String password;/** 私钥 */private String privateKey;/** FTP 服务器地址IP地址*/private String host;/** FTP 端口*/private int port;public SFtpUtil(String username, String password, String host, int port) {this.username = username;this.password = password;this.host = host;this.port = port;}/*** 构造基于秘钥认证的sftp对象* @param username* @param host* @param port* @param privateKey*/public SFtpUtil(String username, String host, int port, String privateKey) {this.username = username;this.host = host;this.port = port;this.privateKey = privateKey;}public SFtpUtil(){}/*** 连接sftp服务器** @throws Exception*/public void login(){try {JSch jsch = new JSch();if (privateKey != null) {// 设置私钥jsch.addIdentity(privateKey);LOG.info("sftp connect by private key file");}session = jsch.getSession(username, host, port);LOG.info("Session is build");if (password != null) {session.setPassword(password);}Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);session.connect();LOG.info("Session is connected");Channel channel = session.openChannel("sftp");channel.connect();LOG.info("channel is connected");sftp = (ChannelSftp) channel;LOG.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));} catch (JSchException e) {LOG.error("Cannot connect to specified sftp server");}}/*** 关闭连接 server*/public void logout(){if (sftp != null) {if (sftp.isConnected()) {sftp.disconnect();LOG.info("sftp is closed already");}}if (session != null) {if (session.isConnected()) {session.disconnect();LOG.info("sshSession is closed already");}}}/*** 将输入流的数据上传到sftp作为文件** @param directory*            上传到该目录* @param sftpFileName*            sftp端文件名* @param input*            输入流* @throws SftpException* @throws Exception*/public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{try {sftp.cd(directory);} catch (SftpException e) {LOG.warn("directory is not exist");sftp.mkdir(directory);sftp.cd(directory);}sftp.put(input, sftpFileName);LOG.info("file upload successful");}/*** 上传单个文件** @param directory*            上传到sftp目录* @param uploadFile*            要上传的文件,包括路径* @throws FileNotFoundException* @throws SftpException* @throws Exception*/public void upload(String directory, String uploadFile) throws FileNotFoundException, SftpException{File file = new File(uploadFile);upload(directory, file.getName(), new FileInputStream(file));}/*** 将byte[]上传到sftp,作为文件。注意:从String生成byte[]是,要指定字符集。** @param directory*            上传到sftp目录* @param sftpFileName*            文件在sftp端的命名* @param byteArr*            要上传的字节数组* @throws SftpException* @throws Exception*/public void upload(String directory, String sftpFileName, byte[] byteArr) throws SftpException{upload(directory, sftpFileName, new ByteArrayInputStream(byteArr));}/*** 将字符串按照指定的字符编码上传到sftp** @param directory*            上传到sftp目录* @param sftpFileName*            文件在sftp端的命名* @param dataStr*            待上传的数据* @param charsetName*            sftp上的文件,按该字符编码保存* @throws UnsupportedEncodingException* @throws SftpException* @throws Exception*/public void upload(String directory, String sftpFileName, String dataStr, String charsetName) throws UnsupportedEncodingException, SftpException{upload(directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));}/*** 下载文件** @param directory*            下载目录* @param downloadFile*            下载的文件* @param saveFile*            存在本地的路径* @throws SftpException* @throws FileNotFoundException* @throws Exception*/public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{if (directory != null && !"".equals(directory)) {sftp.cd(directory);}File file = new File(saveFile);sftp.get(downloadFile, new FileOutputStream(file));LOG.info("file is download successful");}/*** 下载文件* @param directory 下载目录* @param downloadFile 下载的文件名* @return 字节数组* @throws SftpException* @throws IOException* @throws Exception*/public byte[] download(String directory, String downloadFile) throws SftpException, IOException{if (directory != null && !"".equals(directory)) {sftp.cd(directory);}InputStream is = sftp.get(downloadFile);byte[] fileData = IOUtils.toByteArray(is);LOG.info("file is download successful");return fileData;}/*** 获取指定的流* @param directory* @return* @throws SftpException*/public InputStream download(String directory) throws SftpException {return sftp.get(directory);}/*** 删除文件** @param directory*            要删除文件所在目录* @param deleteFile*            要删除的文件* @throws SftpException* @throws Exception*/public void delete(String directory, String deleteFile) throws SftpException{sftp.cd(directory);sftp.rm(deleteFile);}/*** 列出目录下的文件** @param directory*            要列出的目录* @param directory* @return* @throws SftpException*/public Vector<?> listFiles(String directory) throws SftpException {return sftp.ls(directory);}public static void main(String[] args) throws SftpException, IOException {//        SFTPUtil sftp = new SFTPUtil("24kGentle", "123@@321", "192.168.23.34", 22);
//        sftp.login();
//        //byte[] buff = sftp.download("/home/data", "start.sh");
//        //System.out.println(Arrays.toString(buff));
//        File file = new File("D:\\upload\\index.html");
//        InputStream is = new FileInputStream(file);
//
//        sftp.upload("/24kGentle/work", "test_sftp_upload.csv", is);
//        sftp.logout();}
}

SFTP上传下载文件工具类相关推荐

  1. linux上很方便的上传下载文件工具rz和sz

    linux上很方便的上传下载文件工具rz和sz (本文适合linux入门的朋友) ######################################################### # ...

  2. SFTP上传下载文件

    secureCRT SFTP上传/下载文件 远程登陆IP secureCRT会话中点击SFTP 3.cd  /home/dowload       linux平台切换到/home/dowload目录 ...

  3. ftp上传-下载文件通用工具类,已实测

    话不多说直接上代码 package com.springboot.demo.utils;import lombok.extern.slf4j.Slf4j; import org.apache.comm ...

  4. linux上很方便的上传下载文件工具rz和sz使用介绍

    简单说就是,可以很方便地用这两个sz/rz工具,实现Linux下和Windows之间的文件传输(发送和接收),速度大概为10KB/s,适合中小文件.rz/sz 通过Zmodem协议传输数据 一般来说, ...

  5. linux用sz下载文件夹,linux上很方便的上传下载文件工具rz和sz使用介绍

    一般来说,linux服务器大多是通过ssh客户端来进行远程的登陆和管理的,使用ssh登陆linux主机以后,如何能够快速的和本地机器进行文件的交互呢,也就是上传和下载文件到服务器和本地: 与ssh有关 ...

  6. 阿里云oss上传下载删除工具类

    工具类-阿里云oss private static String accessId;private static String accessKey;private static String endp ...

  7. xshell的上传下载文件工具lrzsz

    lrzsz lrzsz是一款xshell提供的一款小程序,在linux中可以代替ftp的上传和下载 安装 yum install -y lrzsz.... Running transaction正在安 ...

  8. springboot上传下载文件(4)--上传下载工具类(已封装)

    因为在做毕设,发现之前的搭建ftp文件服务器,通过ftp协议无法操作虚拟机临时文件,又因为ftp文件服务器搭建的比较麻烦:而 hadoop的HDFS虽然可以实现,但我这里用不到那么复杂的:所以我封装了 ...

  9. C# 使用SFTP的上传下载文件时如何使用代理

    最近遇到一个需求,使用SFTP上传下载文件,由于安全性,需要使用内部代理,在网上找了下,未找到相关代码.就自己整理了一份,实现原理基于 Tamir.SharpSsh.jsch;  部分代码仅供参考. ...

  10. linux lftp下载目录,linux中使用lftp上传下载文件

    lftp是linux中一款ftp服务器相比windows中的ftp显得要复杂不少了,下面我来总结一下lftp文件上传,文件下载,及文件查找等等相关命令吧. lftp连接的几种方法,最常用的是lftp ...

最新文章

  1. Repeater中嵌套DropDownList
  2. SQLServer2008创建新用户 转
  3. 通过投影增强数据模型
  4. 使用Spring Data REST将Spring Data JPA存储库导出为REST服务
  5. LeetCode 2156. 查找给定哈希值的子串(字符串哈希)
  6. asp.net 2.0中允许一次上传多个文件的设计
  7. VB CreateObject函数
  8. 【转载】聪明说话35招
  9. 在 lamp(centos)下配置二级 域名 、虚拟主机
  10. 苹果电脑系统如果删除驱动
  11. 素数表的C++实现:快速进行素数筛选(埃氏筛法)
  12. PHP根据经纬度计算距离
  13. bat批处理文件夹内文件名的提取
  14. .NET MongoDB Driver GridFS 2.2原理及使用示例
  15. 生活污水处理厂工程脱水车间设计、果汁饮料厂工艺流程及车间平面布置CAD设计、水处理车间工艺图、氯乙烯分离车间平面布置图、乳品车间设备布置图、核桃乳饮料厂工艺流程及车间平面布置CAD设计……
  16. h3c交换机配置远程管理_H3C 交换机设置本地用户和telnet远程登录配置 v7 版本...
  17. 系统重构数据同步利器之Canal实战篇
  18. ThinkPad E531加装固态硬盘全过程
  19. 组态软件的开发(C#)
  20. 99%的人都想要的广告拦截软件

热门文章

  1. 计算机公式算加减乘除教程视频,Excel快速计算加减乘除教程 Excel表格公式计算方法...
  2. “抛弃 Gmail!”
  3. 编程篇(002)-js实现一个打点计时器
  4. jquery提交表单验证示例代码
  5. 【论文翻译】预测多关系和异构网络中的链接
  6. html短期总结(至表单)
  7. Windows 7下IE9升级到IE 11,F12控制台不能使用的解决方法
  8. uboot分析之 usb启动
  9. OAuth2授权原理
  10. CSDN论坛如何查看我发布的帖子?