jcraft SFTP 文件上传

一 依赖

    <properties>
        <jsch.version>0.1.54</jsch.version>
    </properties>

 

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>${jsch.version}</version>
        </dependency>

二 工具类

package com.mangoubiubiu.utils;

import com.jcraft.jsch.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class SFTPTransFile {
    private static final String sourceDir = "D:\\hhh.txt";//传输的源端目录
    private static final String destDir = "/apps/images";//传输的目的端目录
    private static final String host = "192.168.56.12";//目的端的IP地址
    private static final int port = 22; //目的端的端口号
    private static final String userName = "root";//目的端的用户名
    private static final String passWord = "root";//目的端的密码

    public static void main(String[] args) throws Exception {
        //连接目的端
        ChannelSftp sftp = connect(host, port, userName, passWord);
        //创建目录
     //   mkdir(destDir, sftp);
        //文件上传
       // uploadFile(new File(sourceDir), destDir, sftp);
        //文件重命名
        //renameFile(destDir,"look.txt","xl.txt",sftp);
        //文件下载
        //downloadFile(destDir,"xl.txt","F:\\xl.txt",sftp);
        //删除文件
        //deleteFile(destDir,"xl.txt",sftp);
    }

    //连接目的端
    public static ChannelSftp connect(String host, int port, String userName, String passWord) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(userName, host, port);
            Session sshSession = jsch.getSession(userName, host, port);
            System.out.println("Session创建成功");
            sshSession.setPassword(passWord);
            System.out.println("密码输入成功");
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            System.out.println("链接参数设置成功");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            System.out.println("Session已连接");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            System.out.println("连接到主机" + host + ".");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sftp;
    }

    //文件上传
    public static void uploadFile(FileInputStream file, String destDir, ChannelSftp sftp) {
        try {
            sftp.cd(destDir);

          //  sftp.put(new FileInputStream(file), file.getName());
            System.out.println("文件上传成功");
        } catch (Exception e) {
            System.out.println("文件上传失败");
        }
    }

    //创建目录
    public static void mkdir(String destDir, ChannelSftp sftp) {
        try {
            sftp.cd(destDir);
            System.out.println("文件夹创建成功: " + destDir);
        } catch (Exception e) {
            System.out.println("进入目录失败,创建目录: " + destDir);
            //创建目录
            String[] dirs = destDir.split("/");
            String tempPath = "";
            for (String dir : dirs) {
                if (dir == null || dir.equals("")) {
                    continue;
                }
                tempPath += "/" + dir;
                try {
                    System.out.println("进入目录[" + tempPath + "]");
                    sftp.cd(tempPath);
                } catch (SftpException ex) {
                    System.out.println("进入目录失败,创建目录[" + tempPath + "]");
                    try {
                        sftp.mkdir(tempPath);
                        sftp.cd(tempPath);
                        System.out.println("进入目录[" + tempPath + "]");
                    } catch (SftpException exc) {
                        System.out.println("进入目录失败,创建目录[" + tempPath + "]");
                    }
                }
            }
        }
    }

    //文件重命名
    public static void renameFile(String destDir, String oldName, String newName, ChannelSftp sftp) {
        try {
            sftp.cd(destDir);
            sftp.rename(oldName, newName);
            System.out.println("文件重命名成功");
        } catch (Exception e) {
            System.out.println("文件重命名失败");
        }
    }

    //文件下载
    public static void downloadFile(String destDir, String downloadFile, String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(destDir);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
            System.out.println("文件下载成功");
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    //文件删除
    public static void deleteFile(String destDir, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(destDir);
            sftp.rm(deleteFile);
            System.out.println("文件删除成功");
        } catch (Exception e) {
            System.out.println("文件删除失败");
        }
    }
}

  

三 业务代码

package com.mangoubiubiu.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import com.jcraft.jsch.ChannelSftp;
import com.mangoubiubiu.entities.Student;
import com.mangoubiubiu.mapper.StudentMapper;
import com.mangoubiubiu.service.StudentService;
import com.mangoubiubiu.utils.SFTPTransFile;
import com.mangoubiubiu.vo.StudentQry;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Queue;
import java.util.UUID;

@Service
@Slf4j
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    private static final String sourceDir = "D:\\hhh.txt";//传输的源端目录
    private static final String destDir = "/apps/images";//传输的目的端目录
    private static final String host = "192.168.56.12";//目的端的IP地址
    private static final int port = 22; //目的端的端口号
    private static final String userName = "root";//目的端的用户名
    private static final String passWord = "root";//目的端的密码

    @Override
    public Student getStudent(String id) {
        return studentMapper.getStuById(id);
    }

    @Override
    public List<Student> getAllStudent(StudentQry qry) {
        return studentMapper.findAll(qry);
    }

    @Override
    public String uploadFile(MultipartFile file)  {
        Long startCurrentTimes=System.currentTimeMillis();
        InputStream inputStream=null;
        String fileName="";
        try {
           String fileType=FileTypeUtil.getType(file.getInputStream());
            if("jpg".equals(fileType) || "png".equals(fileType) || "jpeg".equals(fileType) || "gif".equals(fileType) ){
                log.info("文件类型========={}",fileType);
                // 上传文件流。
                inputStream = file.getInputStream();
                //获取文件名称
                fileName=file.getOriginalFilename();
                //在文件中添加随机值 uuid
                String uuid=   UUID.randomUUID().toString().replaceAll("-","");
                fileName=uuid+fileName;
                ChannelSftp sftp = SFTPTransFile.connect(host, port, userName, passWord);
                sftp.cd(destDir);
                sftp.put(inputStream,fileName);
            }else{
                log.info("文件上传失败,不支持的文件类型========={}",fileType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
            }catch (IOException e){

            }
        }
        Long endCurrentTimes=System.currentTimeMillis();
        log.info("文件上传成功,耗时{}ms",endCurrentTimes-startCurrentTimes);
        return fileName;
    }

    @Override
    public List<Student> getAllStudentT(StudentQry qry) {
        return studentMapper.findStuAllAndRewardOrPunish(qry);
    }


}

 

posted @ 2021-10-24 17:57  KwFruit  阅读(187)  评论(0编辑  收藏  举报