用sftp上传文件至linux服务器

1.项目环境

    框架:springmvc
    项目管理工具:maven

2.必须使用的jar

1   com.jcraft
2   jsch
3   0.1.27
4   test

3.新建一个FileUpDown工具类,在类中添加以下属性

1 //linux服务器基本连接参数
2 String host = "";//ip
3 String username = "";//用户名
4 String password = "";//密码
5 int port = 22;
6 
7 ChannelSftp sftp = null;
8 String remotePath = "/usr/java/file/img/";//服务器上的目标路径
9 String path;//实际路径

    以上属性可以定义为private,可将相关属性值写入*.properties文件,然后读取.

4.连接服务器并获得ChannelSftp

 1 //连接服务器 获得ChannelSftp
 2 public ChannelSftp getSftp() {
 3     try {
 4         JSch jsch = new JSch();
 5         Session session = jsch.getSession(username, host, port);
 6         session.setPassword(password);
 7         Properties properties = new Properties();
 8         properties.put("StrictHostKeyChecking", "no");
 9         session.setConfig(properties);
10         session.connect();
11         Channel channel = session.openChannel("sftp");
12         channel.connect();
13         sftp = (ChannelSftp) channel;
14         System.out.println("连接成功");
15     } catch (Exception e) {
16         System.out.println("连接失败");
17         e.printStackTrace();
18     }
19     return sftp;
20 }

5.上传文件

1 //上传文件
2 public String upLoad(MultipartFile file){
3     ...
4 }

    现在上传的是单个文件,如果上传多个文件时可传入List,MultipartFile是spring提供的类型.
    在方法中写上以下代码:

 1 //上传文件
 2 public String upLoad(MultipartFile file) throws IOException, SftpException {
 3     InputStream is =null;
 4     try{
 5         //要上传的文件名
 6         String filename = file.getOriginalFilename();
 7         String suffix = filename.substring(filename.lastIndexOf("."));
 8         //自动生成文件名
 9         String autofilename = UUID.randomUUID().toString();
10         //生成路径加文件名
11         String path = remotePath + autofilename + suffix;
12         //得到文件输入流
13         is = file.getInputStream();
14         this.getSftp().put(is, path);
15     }finally {
16         //1.关闭输入流
17         //2.断开连接
18         ...
19     }
20     return path;
21 }

6.断开服务

1 public void close() {
2     if (this.sftp != null) {
3         if (this.sftp.isConnected()) {
4             this.sftp.disconnect();
5         } else if (this.sftp.isClosed()) {
6             System.out.println("断开服务成功");
7         }
8     }
9 }

 

posted @ 2017-04-28 01:11  李梦晨  阅读(5832)  评论(0编辑  收藏  举报