SFTP 工具類

這段時間公司在用SFTP服務,而後本身就整理了下sftp的工具,html

流程以下java

一、配置文件linux

##windows環境中的sftp
sftp.win.username=root
sftp.win.password=admin123
sftp.win.uploadPath=/
sftp.win.host=192.168.1.115
sftp.win.privateKey=dsjafkldsjfkajsdswe
sftp.win.port=22
img.win.basePath=http://localhost:8001/

##linux環境中的sftp
sftp.linux.username=
sftp.linux.password=
sftp.linux.uploadPath=
sftp.linux.host=5
sftp.linux.privateKey=
sftp.linux.port=
img.linux.basePath=

二、propertiesUtils工具類用於讀取properties配置文件web

package com.health.web.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.CombinedConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

/**
 * 讀取properties文件的工具類
 * @author Lee
 * @date 2018-10-30
 **/
@Slf4j
public class PropertiesUtils {

    private static CombinedConfiguration config = null;

    public static boolean init(){
        if (config != null)
            return false;
        try {
            Configurations configs = new Configurations();
            config = new CombinedConfiguration();
            config.addConfiguration(configs.properties("common-sftp.properties"));
            return true;
        } catch (ConfigurationException e) {
            log.error("PropertiesUtils:初始化配置文件錯誤", e);
            return false;
        }
    };


    public static void add(Configuration cfg){
        config.addConfiguration(cfg);
    };

    public static boolean containsKey(String arg0) {
        return config.containsKey(arg0);
    }

    public static BigDecimal getBigDecimal(String arg0, BigDecimal arg1) {
        return config.getBigDecimal(arg0, arg1);
    }

    public static BigDecimal getBigDecimal(String arg0) {
        return config.getBigDecimal(arg0);
    }

    public static BigInteger getBigInteger(String arg0, BigInteger arg1) {
        return config.getBigInteger(arg0, arg1);
    }

    public static BigInteger getBigInteger(String arg0) {
        return config.getBigInteger(arg0);
    }

    public static boolean getBoolean(String arg0, boolean arg1) {
        return config.getBoolean(arg0, arg1);
    }

    public static Boolean getBoolean(String arg0, Boolean arg1) {
        return config.getBoolean(arg0, arg1);
    }

    public static boolean getBoolean(String arg0) {
        return config.getBoolean(arg0);
    }

    public static byte getByte(String arg0, byte arg1) {
        return config.getByte(arg0, arg1);
    }

    public static Byte getByte(String arg0, Byte arg1) {
        return config.getByte(arg0, arg1);
    }

    public static byte getByte(String arg0) {
        return config.getByte(arg0);
    }

    public static double getDouble(String arg0, double arg1) {
        return config.getDouble(arg0, arg1);
    }

    public static Double getDouble(String arg0, Double arg1) {
        return config.getDouble(arg0, arg1);
    }

    public static double getDouble(String arg0) {
        return config.getDouble(arg0);
    }

    public static float getFloat(String arg0, float arg1) {
        return config.getFloat(arg0, arg1);
    }

    public static Float getFloat(String arg0, Float arg1) {
        return config.getFloat(arg0, arg1);
    }

    public static float getFloat(String arg0) {
        return config.getFloat(arg0);
    }

    public static int getInt(String arg0, int arg1) {
        return config.getInt(arg0, arg1);
    }

    public static int getInt(String arg0) {
        return config.getInt(arg0);
    }

    public static Integer getInteger(String arg0, Integer arg1) {
        return config.getInteger(arg0, arg1);
    }

    public static Iterator<?> getKeys() {
        return config.getKeys();
    }

    public static Iterator<?> getKeys(String arg0) {
        return config.getKeys(arg0);
    }

    public static List<?> getList(String arg0, List<?> arg1) {
        return config.getList(arg0, arg1);
    }

    public static List<?> getList(String arg0) {
        return config.getList(arg0);
    }

    public static long getLong(String arg0, long arg1) {
        return config.getLong(arg0, arg1);
    }

    public static Long getLong(String arg0, Long arg1) {
        return config.getLong(arg0, arg1);
    }

    public static long getLong(String arg0) {
        return config.getLong(arg0);
    }

    public static Properties getProperties(String arg0) {
        return config.getProperties(arg0);
    }

    public static Object getProperty(String arg0) {
        return config.getProperty(arg0);
    }

    public static short getShort(String arg0, short arg1) {
        return config.getShort(arg0, arg1);
    }

    public static Short getShort(String arg0, Short arg1) {
        return config.getShort(arg0, arg1);
    }

    public static short getShort(String arg0) {
        return config.getShort(arg0);
    }

    public static String getString(String arg0, String arg1) {
        return config.getString(arg0, arg1);
    }

    public static String getString(String arg0) {
        return config.getString(arg0);
    }

    public static String[] getStringArray(String arg0) {
        return config.getStringArray(arg0);
    }

    public static boolean isEmpty() {
        return config.isEmpty();
    }

}

三、SFTPUtils工具類數據庫

package com.health.web.common.utils;

import com.jcraft.jsch.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Properties;
import java.util.UUID;
import java.util.Vector;

/**
 * SFTP工具類
 * @author Lee
 * @date 2018-10-30
 **/
@Slf4j
@Data
public class SFTPUtil {

    private ChannelSftp sftp;

    private Session session;

    //SFTP用戶名
    private String username;

    //SFTP用戶密碼
    private String password;

    //SFTP上傳基礎路徑
    private String uploadPath;

    //SFTP私鑰
    private String privateKey;

    //SFTP服務地址
    private String host;

    //SFTP端口
    private int port;

    //圖片訪問基本地址
    private String basePath;

    public SFTPUtil(){
        super();
    }

    //構造基於密碼認證的sftp對象--非配置文件加載
    public SFTPUtil(String username, String password, String host, int port,String uploadPath) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
        this.uploadPath = uploadPath;
    }

    //構造基於祕鑰認證的sftp對象--非配置文件加載
    public SFTPUtil(String username, String host, int port, String privateKey,String uploadPath) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.privateKey = privateKey;
        this.uploadPath = uploadPath;
    }

    //初始化數據
    public void  SFTPUtilInit(){
        boolean res = PropertiesUtils.init();
        Boolean ifWin = SFTPUtil.isWindows();
        if(ifWin){
            username = PropertiesUtils.getString("sftp.win.username");
            password = PropertiesUtils.getString("sftp.win.password");
            port = PropertiesUtils.getInt("sftp.win.port");
            uploadPath = PropertiesUtils.getString("sftp.win.uploadPath");
            host = PropertiesUtils.getString("sftp.win.host");
            basePath = PropertiesUtils.getString("img.win.basePath");
        }else{
            username = PropertiesUtils.getString("sftp.linux.username");
            password = PropertiesUtils.getString("sftp.linux.password");
            port = PropertiesUtils.getInt("sftp.linux.port");
            uploadPath = PropertiesUtils.getString("sftp.linux.uploadPath");
            host = PropertiesUtils.getString("sftp.linux.host");
            basePath = PropertiesUtils.getString("img.linux.basePath");
        }
    }


    //判斷是不是windows系統
    public static Boolean isWindows(){
        String op = System.getProperties().getProperty("os.name");
        if (StringUtils.isNotBlank(op) && op.toLowerCase().startsWith("win")) {
            return true;
        } else {
            return false;
        }
    }

    //鏈接SFTP服務
    public Boolean login(){
        //初始化數據
        SFTPUtilInit();
        try {
            JSch jsch = new JSch();
            if (privateKey != null) {
                jsch.addIdentity(privateKey);// 設置私鑰
            }

            session = jsch.getSession(username, host, 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();

            sftp = (ChannelSftp) channel;

        } catch (JSchException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //關閉Server服務
    public void logout(){
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    /**
     * 將輸入流的數據上傳到sftp做爲文件。文件完整路徑=basePath+directory
     * @param directory  上傳到該目錄
     * @param sftpFileName  sftp端文件名
     * @param input   輸入流
     */
    public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{
        try {
            sftp.cd(uploadPath);
            sftp.cd(directory);
        } catch (SftpException e) {
            //目錄不存在,則建立文件夾
            String [] dirs=directory.split(File.separator);
            String tempPath=uploadPath;
            for(String dir:dirs){
                if(null== dir || "".equals(dir)) continue;
                tempPath+=File.separator+dir;
                try{
                    sftp.cd(tempPath);
                }catch(SftpException ex){
                    sftp.mkdir(tempPath);
                    sftp.cd(tempPath);
                }
            }
        }
        sftp.put(input, sftpFileName);  //上傳文件
    }


    /**
     * 下載文件。
     * @param directory 下載目錄
     * @param downloadFile 下載的文件
     * @param saveFile 存在本地的路徑
     */
    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
        sftp.cd(uploadPath);
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        File file = new File(saveFile);
        sftp.get(downloadFile, new FileOutputStream(file));
    }



    /**
     * 下載文件
     * @param directory 下載目錄
     * @param downloadFile 下載的文件名
     * @return 字節數組
     */
    public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
        sftp.cd(uploadPath);
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        InputStream is = sftp.get(downloadFile);

        byte[] fileData = IOUtils.toByteArray(is);
        return fileData;
    }


    /**
     * 刪除文件
     * @param directory 要刪除文件所在目錄
     * @param deleteFile 要刪除的文件
     */
    public void delete(String directory, String deleteFile) throws SftpException{
        sftp.cd(uploadPath);
        sftp.cd(directory);
        sftp.rm(deleteFile);
    }

    /**
     * 列出目錄下的文件
     * @param directory 要列出的目錄
     */
    public Vector<?> listFiles(String directory) throws SftpException {
        sftp.cd(uploadPath);
        return sftp.ls(directory);
    }

    public static void main(String[] args) {
        SFTPUtil util = new SFTPUtil();
        Boolean loginRes = util.login();
        if(loginRes){
            File file = new File("G:/a.jpg");
            InputStream is = null;
            try {
                is = new FileInputStream(file);
                util.upload("/jialong/wenhao",UUID.randomUUID().toString()+".jpg",is);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                util.logout();
            }
        }

    }

}

四、圖片批量上傳apache

/**
     * 保存-上傳照片-批量
     */
    @RequestMapping("/addBatch")
    public R save( @RequestParam(value="file",required=false) MultipartFile[] file,HttpServletRequest request){
        UmsMember userHolder = ThreadUtils.getUserHolder();
        if(userHolder!=null && StringUtils.isNotBlank(userHolder.getUserCode())){

            if (file!=null && file.length>0) {

                SFTPUtil util = new SFTPUtil();
                Boolean loginRes = util.login();

                //數據庫存儲
                List<UserCompImg> userCompImgList = new ArrayList<>();
                UserCompImg userCompImg = null;
                if(loginRes){

                    String returnUrl = File.separator+"userCompImg"+File.separator;//存儲路徑
                    InputStream is = null;
                    BufferedImage image = null;
                    try {
                        for (int i = 0; i < file.length; i++) {
                            String fileName=file[i].getOriginalFilename();//獲取文件名加後綴
                            if(fileName!=null&&fileName!=""){
                                String path = request.getSession().getServletContext().getRealPath(returnUrl); //文件存儲位置
                                String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件後綴
                                fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+suffix;//新的文件名
                            }
                            is = file[i].getInputStream();
                            util.upload(returnUrl,fileName,is);

                            userCompImg = new UserCompImg();
                            userCompImg.setUserCompImgCode(UUID.randomUUID().toString());
                            userCompImg.setUserCode(userHolder.getUserCode());
                            userCompImg.setImgUrl(returnUrl+File.separator+fileName);
                            userCompImg.setCreateTime(new Date());
                            userCompImg.setUpdateTime(new Date());
                            userCompImgList.add(userCompImg);
                        }
                    } catch (IOException e) {
                        log.error("====>file轉inputStream失敗");
                        e.printStackTrace();
                    } catch (SftpException e) {
                        log.error("====>sftp上傳失敗");
                        e.printStackTrace();
                    } finally {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        util.logout();
                    }

                }else{
                    log.error("====>sftp鏈接失敗");
                    return R.error(PublicResultConstant.FAILED.result, PublicResultConstant.FAILED.getMsg());
                }

                //批量插入數據庫
                Integer res = userCompImgService.addBatchUserCompImg(userCompImgList);
                if(res>0){
                    return R.ok();
                }else{
                    return R.error(PublicResultConstant.FAILED.result, PublicResultConstant.FAILED.getMsg());
                }

            }

        }
        return R.error(PublicResultConstant.PARAM_ERROR.result, PublicResultConstant.PARAM_ERROR.getMsg());
    }

五、Nginx配置windows

server {
        listen       8001;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
		
        location / {
            root   E:/FileServer/;
            index  index.html index.htm;
			add_header 'Access-Control-Allow-Origin' *;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }
相關文章
相關標籤/搜索