sftp



import java.util.Map;
import java.util.Properties;



import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class SFTPChannel {

    private Session session = null;
    private Channel channel = null;

    private static final Logger logger = Logger.getLogger(SFTPChannel.class.getName());

    public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {

        String ftpHost = sftpDetails.get(SFTParam.SFTP_REQ_HOST);
        String port = sftpDetails.get(SFTParam.SFTP_REQ_PORT);
        String ftpUserName = sftpDetails.get(SFTParam.SFTP_REQ_USERNAME);
        String ftpPassword = sftpDetails.get(SFTParam.SFTP_REQ_PASSWORD);

        int ftpPort = SFTParam.SFTP_DEFAULT_PORT;
        if(port != null && !port.equals("")) {
            ftpPort = Integer.valueOf(port);
        }

        JSch jsch = new JSch(); // 创建JSch对象
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名,主机ip,端口获取一个Session对象

        logger.debug("Session created.");

        if(ftpPassword != null) {
            session.setPassword(ftpPassword); // 设置密码
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(timeout); // 设置timeout时间
        session.connect(); // 通过Session建立链接
        logger.debug("Session connected.");

        logger.debug("Opening Channel.");

        channel = session.openChannel("sftp"); // 打开SFTP通道
        channel.connect(); // 建立SFTP通道的连接

        logger.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
                + ", returning: " + channel);
        return (ChannelSftp) channel;
    }

    public void closeChannel() throws Exception {
          if(channel != null){
               channel.disconnect();
          }

          if(session != null){
              session.disconnect();
          }
    }
}

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import com.jcraft.jsch.SftpProgressMonitor;

public class FileProgressMonitor extends TimerTask implements SftpProgressMonitor {

    private long progressInterval = 5 * 1000; // 默认间隔时间为5秒

    private boolean isEnd = false; // 记录传输是否结束

    private long transfered; // 记录已传输的数据总大小

    private long fileSize; // 记录文件总大小

    private Timer timer; // 定时器对象

    private boolean isScheduled = false; // 记录是否已启动timer记时器

    public FileProgressMonitor(long fileSize) {
        this.fileSize = fileSize;
    }

    @Override
    public void run() {
        if (!isEnd()) { // 判断传输是否已结束
            System.out.println("Transfering is in progress.");
            long transfered = getTransfered();
            if (transfered != fileSize) { // 判断当前已传输数据大小是否等于文件总大小
                System.out.println("Current transfered: " + transfered + " bytes");
                sendProgressMessage(transfered);
            } else {
                System.out.println("File transfering is done.");
                setEnd(true); // 如果当前已传输数据大小等于文件总大小,说明已完成,设置end
            }
        } else {
            System.out.println("Transfering done. Cancel timer.");
            stop(); // 如果传输结束,停止timer记时器
            return;
        }
    }

    public void stop() {
        System.out.println("Try to stop progress monitor.");
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
            isScheduled = false;
        }
        System.out.println("Progress monitor stoped.");
    }

    public void start() {
        System.out.println("Try to start progress monitor.");
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(this, 1000, progressInterval);
        isScheduled = true;
        System.out.println("Progress monitor started.");
    }

    /** * 打印progress信息 * @param transfered */
    private void sendProgressMessage(long transfered) {
        if (fileSize != 0) {
            double d = ((double)transfered * 100)/(double)fileSize;
            DecimalFormat df = new DecimalFormat( "#.##"); 
            System.out.println("Sending progress message: " + df.format(d) + "%");
        } else {
            System.out.println("Sending progress message: " + transfered);
        }
    }

    /** * 实现了SftpProgressMonitor接口的count方法 */
    public boolean count(long count) {
        if (isEnd()) return false;
        if (!isScheduled) {
            start();
        }
        add(count);
        return true;
    }

    /** * 实现了SftpProgressMonitor接口的end方法 */
    public void end() {
        setEnd(true);
        System.out.println("transfering end.");
    }

    private synchronized void add(long count) {
        transfered = transfered + count;
    }

    private synchronized long getTransfered() {
        return transfered;
    }

    public synchronized void setTransfered(long transfered) {
        this.transfered = transfered;
    }

    private synchronized void setEnd(boolean isEnd) {
        this.isEnd = isEnd;
    }

    private synchronized boolean isEnd() {
        return isEnd;
    }

    public void init(int op, String src, String dest, long max) {
        // Not used for putting InputStream
    }
}

public class SFTParam {

    public static final String SFTP_REQ_HOST = "host";
    public static final String SFTP_REQ_PORT = "port";
    public static final String SFTP_REQ_USERNAME = "username";
    public static final String SFTP_REQ_PASSWORD = "password";
    public static final int SFTP_DEFAULT_PORT = 22;
    public static final String SFTP_REQ_LOC = "location";


    public static final String FILEPATH = "filepath" ;

    public static final String FILE_NAME =  "filename" ;

}

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;



@Controller
public class SftpController {

     @Autowired
     private SFTPChannel channel   ;

     @ResponseBody
     @RequestMapping(value="/sftp/upload" , produces="text/html;charset=UTF-8")
     public  String upLoad(@RequestParam("file") MultipartFile[] files  ,
                           @RequestParam("host") String host ,
                           @RequestParam("port") String port ,
                           @RequestParam("username") String username ,
                           @RequestParam("password") String password , 
                           @RequestParam("targetPath") String targetPath ) throws Exception{

             JSONObject responseStr  =  new JSONObject() ;

             Map<String, String> sftpDetails = new HashMap<String, String>();
             // 设置主机ip,端口,用户名,密码
             sftpDetails.put(SFTParam.SFTP_REQ_HOST, host) ; 
             sftpDetails.put(SFTParam.SFTP_REQ_USERNAME, username) ; 
             sftpDetails.put(SFTParam.SFTP_REQ_PASSWORD, password) ; 
             sftpDetails.put(SFTParam.SFTP_REQ_PORT, port) ; 

             ChannelSftp chSftp = new ChannelSftp() ; 
             try{
                    chSftp = channel.getChannel(sftpDetails, 600) ;
             }catch(JSchException e){
                    responseStr.put("retCode", "9999") ;
                    responseStr.put("retMsg", "连接不上sftp!") ;
                    chSftp.quit();
                    channel.closeChannel();
                    return responseStr.toJSONString()  ;
             }

         try{
             int k =  0 ;
             for(MultipartFile file : files){
                      String fileName = file.getOriginalFilename();
                      if(fileName == null || fileName.equals(""))  continue ;

                      k++ ;
                      String dst = targetPath + "/" + fileName     ; // "/nfsc/appsystem/liyang"
                      chSftp.put(file.getInputStream() , dst , new FileProgressMonitor(file.getSize()), ChannelSftp.OVERWRITE); // 代码段2 
             }

             if(k == 0){
                    responseStr.put("retCode", "9999") ;
                    responseStr.put("retMsg", "上传文件不能为空!") ;
                    return responseStr.toJSONString()  ;
             }
         }catch(SftpException e){
                responseStr.put("retCode", "9999") ;
                responseStr.put("retMsg", "上传失败!") ;
                chSftp.quit();
                channel.closeChannel();
                return responseStr.toJSONString()  ; 
         }


         chSftp.quit();
         channel.closeChannel(); 
         responseStr.put("retCode", "0000") ;
         responseStr.put("retMsg", "") ;

         return responseStr.toJSONString()  ;
    }


     @RequestMapping(value="/sftp/download" , produces="text/html;charset=UTF-8")
     @ResponseBody
     public void download(@RequestParam("host") String host ,
                           @RequestParam("port") String port ,
                           @RequestParam("username") String username ,
                           @RequestParam("password") String password , 
                           @RequestParam("targetPath") String targetPath ,
                           HttpServletResponse response) throws Exception {


         Map<String, String> sftpDetails = new HashMap<String, String>();
         ChannelSftp chSftp = null   ;
         String dst = null ;
         OutputStream out ;

         String realName = targetPath.substring(targetPath.lastIndexOf("/")  + 1 )  ;

         try{
                // 设置主机ip,端口,用户名,密码
                sftpDetails.put(SFTParam.SFTP_REQ_HOST, host) ; 
                sftpDetails.put(SFTParam.SFTP_REQ_USERNAME, username) ; 
                sftpDetails.put(SFTParam.SFTP_REQ_PASSWORD, password) ; 
                sftpDetails.put(SFTParam.SFTP_REQ_PORT, port) ; 
                chSftp = channel.getChannel(sftpDetails, 6000)  ;
                SftpATTRS attr = chSftp.stat(targetPath) ;
                long fileSize = attr.getSize() ;
                dst =  realName   ;
                out = new FileOutputStream(dst) ;
                chSftp.get(targetPath, out, new FileProgressMonitor(fileSize)) ; // 代码段2
          } 
          catch (Exception e){
                if(chSftp != null) chSftp.quit();
                channel.closeChannel();
          } 
          finally{
                if(chSftp != null) chSftp.quit();
                channel.closeChannel();
          }

          File file = new File(dst);
          int BUFFER_SIZE = 4096;
          InputStream in = null;
          OutputStream out2 = null;
          try{ 
                    response.setHeader("retcode", "0000") ;
                    response.setCharacterEncoding("utf-8") ; 
                    response.setHeader("Content-disposition", "attachment; filename= "  + realName )  ;
                    response.setContentType("application/octet-stream");
                    response.setContentLength((int) file.length());
                    response.setHeader("Accept-Ranges", "bytes");
                    in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
                    out2 = new BufferedOutputStream(response.getOutputStream());
                    byte[] buffer = new byte[BUFFER_SIZE];
                    int readLength = 0;
                    while ((readLength=in.read(buffer)) > 0) {
                         byte[] bytes = new byte[readLength];
                         System.arraycopy(buffer, 0, bytes, 0, readLength);
                         out2.write(bytes);
                    } 
                    out2.flush();
           }
           catch(Exception e){
                  throw e ;

           }
           finally
           {
                if (in != null)
                {
                         try {
                             in.close();
                         } catch (IOException e) {
                             throw e ;
                         }
                }

                if (out2 != null) {
                         try {
                             out2.close();
                         } catch (IOException e) {
                             throw e ;
                         }
                }

         }

         file.delete()  ; 
    } 


     @RequestMapping(value="/sftp/downloadCheck" , produces="text/html;charset=UTF-8")
     @ResponseBody
     public String candownload(@RequestParam("host") String host ,
                               @RequestParam("port") String port ,
                               @RequestParam("username") String username ,
                               @RequestParam("password") String password , 
                               @RequestParam("targetPath") String targetPath ) throws Exception{  

            JSONObject responseStr  =  new JSONObject() ;
            Map<String, String> sftpDetails = new HashMap<String, String>();
            // 设置主机ip,端口,用户名,密码
            sftpDetails.put(SFTParam.SFTP_REQ_HOST, host) ;
            sftpDetails.put(SFTParam.SFTP_REQ_USERNAME, username) ;
            sftpDetails.put(SFTParam.SFTP_REQ_PASSWORD, password) ;
            sftpDetails.put(SFTParam.SFTP_REQ_PORT, port);

            ChannelSftp chSftp = new ChannelSftp()  ;
            try{
                chSftp = channel.getChannel(sftpDetails, 600)  ;
            }
            catch(JSchException e){
                responseStr.put("retCode", "9999") ;
                responseStr.put("retMsg", "连接不上sftp!") ;
                chSftp.quit() ;
                return  responseStr.toJSONString()  ;
            }

            SftpATTRS attr  ;
            try{
                attr = chSftp.stat(targetPath) ;
            }
            catch(SftpException e){
                 responseStr.put("retCode", "9999") ;
                 responseStr.put("retMsg", "没有此文件,下载失败!") ;
                 chSftp.quit() ;
                 return  responseStr.toJSONString()  ;
            }


            chSftp.quit();
            channel.closeChannel();

            responseStr.put("retCode", "0000") ;
            responseStr.put("retMsg", "")  ;
            return  responseStr.toJSONString()  ;
     }  
}
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8" />
       <property name="maxUploadSize" value="10485760000" />
       <property name="maxInMemorySize" value="40960" />
 </bean>    

你可能感兴趣的:(sftp)