好用的Spring Boot实现SFTP上传文件工具类

1.工厂方法

package com.xx.xxx.xx.factory;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * SFTP工厂类,用于获取SFTP的连接
 * @author 奇点_
 */
@Slf4j
@Component
public class SFTPConnectionFactory {
	// 远程服务器地址
	@Value("${FTP.FtpHost}")
	private String hostName;
	// 端口
	@Value("${FTP.FtpPort}")
	private int port = 22;
	// 用户名
	@Value("${FTP.UserName}")
	private String userName;
	// 密码
	@Value("${FTP.PassWord}")
	private String password;

	private static String privateKey;

	private ChannelSftp client;
	private Session session;

	public synchronized ChannelSftp makeConnection(){
		
		if(client==null||session==null||!client.isConnected()||!session.isConnected()){
			try {    
				JSch jsch = new JSch();    
				if (privateKey != null) {    
					jsch.addIdentity(privateKey);// 设置私钥    
				}    
				session = jsch.getSession(userName, hostName, port);
				if (password != null) {    
					session.setPassword(password);      
				}    
				Properties config = new Properties();    
				config.put("StrictHostKeyChecking", "no");    
				session.setConfig(config);    
				session.connect();    
				Channel channel = session.openChannel("sftp");    
				channel.connect();    
				client = (ChannelSftp) channel;    
				log.info("sftp服务器连接成功");
			} catch (JSchException e) {
				log.error("sftp登录失败,检测登录ip,端口号,用户名密码是否正确,错误信息为"+e.getMessage());
			} 
		}
		    
		     return client;
	}
	/**  
     * 关闭连接 server   
     */    
    public  void logout(){    
        if (client != null) {    
            if (client.isConnected()) {    
            	client.disconnect();    
            }    
        }    
        if (session != null) {    
            if (session.isConnected()) {    
                session.disconnect();    
            }    
        }    
    }


}

2.上传、下载、删除方法

package com.xxx.xxx.xxx.utils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import com.pig4cloud.pigx.admin.factory.SFTPConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class SFTPClientUtils {
	private static int downloadSleep = 100;
	private static int downloadRetry = 10;
	private static int uploadSleep = 100;
	private static int uploadRettry = 10;

	@Autowired
	private SFTPConnectionFactory sftpConnectionFactory;


	/**
	 * 文件上传
	 * 将文件对象上传到sftp作为文件。文件完整路径=basePath+directory
	 * 目录不存在则会上传文件夹
	 * @param remotePath  服务器的基础路径
	 * @param remoteFilename  远程文件名
	 * @param localFileName  需要上传的文件路径
	 */
	public synchronized  boolean uploadFile(String remotePath, String remoteFilename, String localFileName){
		boolean result = false;
		Integer i = 0;
		while(!result){
			ChannelSftp sftp = sftpConnectionFactory.makeConnection();
			try {
				sftp.cd(remotePath);
			} catch (SftpException e) {
				log.info("sftp文件上传,目录不存在开始创建");
			}
			try {
				File file = new File(localFileName);
				sftp.put(new FileInputStream(file) ,remoteFilename);
				if(i>0){
					log.info("sftp重试文件上传成功,ftp路径:"+remotePath+",文件名称:"+remoteFilename);
				}else{
					log.info("sftp文件上传成功,ftp路径为"+remotePath+",文件名称:"+remoteFilename);
				}
				result = true;
			} catch (Exception e) {
				i++;
				log.error("sftp文件上传失败,重试中。。。第"+i+"次,错误信息"+e.getMessage());
				if(i>uploadRettry){
					log.error("sftp文件上传失败,超过重试次数结束重试,错误信息"+e.getMessage());
					return result;
				}
				try {
					TimeUnit.MILLISECONDS.sleep(uploadSleep);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}

		}

		return result;
	}
	/**
	 * 文件上传  
     * 将文件对象上传到sftp作为文件。文件完整路径=basePath+directory
     * 目录不存在则会上传文件夹 
     * @param basePath  服务器的基础路径  
     * @param directory  上传到该目录   
     * @param filePath  sftp端文件名
     */
    public synchronized  boolean upload(String basePath,String directory, String filePath){
    	boolean result = false;
    	Integer i = 0;
        while(!result){
        	ChannelSftp sftp = sftpConnectionFactory.makeConnection();
        	try {     
                sftp.cd(basePath);  
                sftp.cd(directory);    
            } catch (SftpException e) {   
            	log.info("sftp文件上传,目录不存在开始创建");
                String [] dirs=directory.split("/");  
                String tempPath=basePath;  
                for(String dir:dirs){  
                    if(null== dir || "".equals(dir)) {
						continue;
					}
                    tempPath+="/"+dir;  
                    try{   
                        sftp.cd(tempPath);  
                    }catch(SftpException ex){  
                        try {
    						sftp.mkdir(tempPath);
    						sftp.cd(tempPath);  
    					} catch (SftpException e1) {
    						log.error("sftp文件上传,目录创建失败,错误信息:"+e1.getMessage()+ex.getMessage());
    					}  
                    }  
                }  
            }    
            try {
            	File file = new File(filePath);
    			sftp.put(new FileInputStream(file) , file.getName());
    			if(i>0){
					log.info("sftp重试文件上传成功,ftp路径:"+basePath+directory+",文件名称:"+file.getName());
				}else{
					log.info("sftp文件上传成功,ftp路径为"+basePath+directory+",文件名称:"+file.getName());
				}
    			result = true;
    		} catch (Exception e) {
    			i++;
    			log.error("sftp文件上传失败,重试中。。。第"+i+"次,错误信息"+e.getMessage());
				if(i>uploadRettry){
					log.error("sftp文件上传失败,超过重试次数结束重试,错误信息"+e.getMessage());
					return result;
				}
    			try {
					TimeUnit.MILLISECONDS.sleep(uploadSleep);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
    		}  
            
        }
    	
        return result;
    }   
    /**  
     * 下载文件。 
     * @param directory 下载目录   
     * @param downloadFile 下载的文件  
     * @param saveFile 存在本地的路径  
     */      
    public synchronized  boolean download(String directory, String downloadFile, String saveFile){
    	boolean result = false;
    	Integer i = 0;
    	while(!result){
    		ChannelSftp sftp = sftpConnectionFactory.makeConnection();
    		if (directory != null && !"".equals(directory)) {    
    			try {
    				sftp.cd(directory);
    			} catch (SftpException e) {
    				log.error("sftp文件下载,目录不存在,错误信息"+e.getMessage());
    			}    
    		}    
    		File file = new File(saveFile+downloadFile); 
    		FileOutputStream fileOutputStream = null;
    		try {
    			fileOutputStream = new FileOutputStream(file);
    		} catch (FileNotFoundException e1) {
    			log.error("sftp文件下载失败,本地目录不存在"+e1.getMessage());
    		}
    		try {
    			sftp.get(downloadFile, fileOutputStream);
				 if(i>0){
				    	log.info("sftp文件重试下载成功,sftp地址:"+directory+",本地文件地址:"+saveFile);	
				    }else{
				    	log.info("sftp文件下载成功,sftp地址:"+directory+",本地文件地址:"+saveFile);
				    }
    			result = true;
    		} catch (SftpException e1) {
    			i++;
				log.error("sftp文件下载失败,重试中。。。第"+i+"次,错误信息"+e1.getMessage());
				if(i>downloadRetry){
					log.error("ftp文件下载失败,超过重试次数结束重试,错误信息"+e1.getMessage());
					return result;
				}
				try {
					TimeUnit.MILLISECONDS.sleep(downloadSleep);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
    		}finally {
    			try {
    				fileOutputStream.close();
    			} catch (IOException e) {
    				
    				e.printStackTrace();
    			}
    		}
    	}
        return result;
    }    
    
      
      
    /**  
     * 删除文件  
     * @param directory 要删除文件所在目录  
     * @param deleteFile 要删除的文件  
     */    
    public synchronized  boolean delete(String directory, String deleteFile){
    	boolean result = false;
    	ChannelSftp sftp = sftpConnectionFactory.makeConnection();
    	try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    
        result = true;
        return result;
    }
	public static int getDownloadSleep() {
		return downloadSleep;
	}
	public static void setDownloadSleep(int downloadSleep) {
		SFTPClientUtils.downloadSleep = downloadSleep;
	}
	public static int getDownloadRetry() {
		return downloadRetry;
	}
	public static void setDownloadRetry(int downloadRetry) {
		SFTPClientUtils.downloadRetry = downloadRetry;
	}
	public static int getUploadSleep() {
		return uploadSleep;
	}
	public static void setUploadSleep(int uploadSleep) {
		SFTPClientUtils.uploadSleep = uploadSleep;
	}
	public static int getUploadRettry() {
		return uploadRettry;
	}
	public static void setUploadRettry(int uploadRettry) {
		SFTPClientUtils.uploadRettry = uploadRettry;
	}    
      
      
   
        
   
}

调用方式。Spring 注入调用

@Autowired
private SFTPClientUtils sftpClientUtils;

记录SFTP上传文件日常
注意事项:
1.两个服务操作同一个文件夹,不要用同一个账号

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值