sftp上傳

公司用到得到了sptp上傳   寫完後 記下來 方便下次使用


有上傳 下載  支持多文件上傳  不過不知道通過spring 的  MultipartFile  如何得到上傳文件的絕對路徑  就自己在項目上建立了個 upload文件夾  用來將上傳的代碼存到裏面

在從本地服務器存到ftp服務器上  大笑有點low    不過還是用得上的  




package testoone;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

public class FtpUtil {
    // private static final Logger LOG = LoggerFactory.getLogger(FtpUtil.class);
    /**
     *
     * getConnect(獲取sftp連接)<br/>
     *
     * @param host
     *            IpAddress
     * @param port
     *            端口
     * @param username
     *            登錄名
     * @param password
     *            登錄密碼
     * @throws SysException
     * @return ChannelSftp
     */
    public static  ChannelSftp getConnect(String host, int port, String username, String password) throws Exception {
        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            return (ChannelSftp) channel;
        } catch (JSchException e) {
            throw new Exception("連接sftp失敗");
        }
    }

    @SuppressWarnings("unused")
    private static void closeChannel(Channel channel) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }

    @SuppressWarnings("unused")
    private static void closeSession(Session session) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    /**
     * 文件下載
     *
     * @param directory
     * @param downloadFile
     * @param saveFile
     * @param sftp
     */
    public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上傳單個文件
     *
     * @param directory
     *            上傳的目錄
     * @param uploadFile
     *            要上傳的文件
     *
     * @throws Exception
     */
    
    @SuppressWarnings("rawtypes")
    public static  void upload(String directory, String pathName, ChannelSftp sftp) throws Exception {
        Vector content = sftp.ls(directory);
        if (content == null) {
            sftp.mkdir(directory);
        }
        File file = new File(pathName);
        sftp.cd(directory);
        try {
            sftp.put(new FileInputStream(file), file.getName());
        } catch (Exception e) {
            throw new Exception("文件上傳失敗");
        }
    }

    /**
     * 下載單個文件
     *
     * @param directory
     *            下載目錄
     * @param downloadFile
     *            下載的文件
     * @param saveDirectory
     *            存在本地的路徑
     *
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public void download(ChannelSftp sftp, String directory, String downloadFile, String saveDirectory)
            throws Exception {

        Vector content = sftp.ls(directory);
        if (content == null) {
            sftp.mkdir(directory);
        }
        String saveFile = saveDirectory + "//" + downloadFile;

        sftp.cd(directory);

        File file = new File(saveFile);
        sftp.get(downloadFile, new FileOutputStream(file));
    }

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

    /**
     * 列出目錄下的文件
     *
     * @param directory
     *            要列出的目錄
     *
     * @return list 文件名列表
     *
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public List<String> listFiles(String directory, ChannelSftp sftp) throws Exception {

        Vector fileList;
        List<String> fileNameList = new ArrayList<String>();

        fileList = sftp.ls(directory);
        Iterator it = fileList.iterator();

        while (it.hasNext()) {
            String fileName = ((LsEntry) it.next()).getFilename();
            if (".".equals(fileName) || "..".equals(fileName)) {
                continue;
            }
            fileNameList.add(fileName);

        }

        return fileNameList;
    }

    /**
     * 更改文件名
     *
     * @param directory
     *            文件所在目錄
     * @param oldFileNm
     *            原文件名
     * @param newFileNm
     *            新文件名
     *
     * @throws Exception
     */
    public void rename(String directory, String oldFileNm, String newFileNm, ChannelSftp sftp) throws Exception {
        sftp.cd(directory);
        sftp.rename(oldFileNm, newFileNm);
    }

    public void cd(String directory, ChannelSftp sftp) throws Exception {
        sftp.cd(directory);
    }

    public InputStream get(String directory, ChannelSftp sftp) throws Exception {
        InputStream streatm = sftp.get(directory);
        return streatm;
    }
/**
 * 上傳文件支持多文件上傳
 * @param files  上傳的文件
 * @param folderPath  本地服務器目錄
 */
    public static void upload(CommonsMultipartFile[] files,String folderPath){
        //文件上傳的目錄
        String directory="";
        
        //鏈接ftp的參數
        String url="";
        String username="";
        String password="";
        int port=0;
        
        //循環判斷文件
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    byte[] b = new byte[1024];
                    InputStream is = file.getInputStream();
                    OutputStream os = new FileOutputStream(folderPath + File.separator + "upload" + file.getName());
                    int len = 0;
                    while ((len = is.read(b)) > 0) {
                        os.write(b);
                    }
                    is.close();
                    os.close();

                    //進行ftp操作
                     ChannelSftp sftp = null;
                      
                      sftp =getConnect(url, port, username, password);    
                      upload(directory, folderPath + File.separator + "upload" + file.getName(), sftp);                
                    
                } catch (Exception e) {
                    new Exception(e.toString());
                }
                
                

            }
        }
        
        
        
    }
    
    
    
    /**
     * 測試是否連接成功
     */
    public static void main(String[] args) {
        /*
         * ChannelSftp sftp = null; try { sftp = getConnect("10.1.234.194", 22,
         * "devusr01", "devusr#01_Infra@8899"); download(
         * "/aifs01/devusers/devusr01/domains/IT_MIS1TD1/servers/MIS1TD1_DEVCM-S1/conf"
         * ,"logging.properties","G:\\test\\logging.properties",sftp); } catch
         * (Exception e) { e.printStackTrace(); }
         */
        ChannelSftp sftp = null;
        try {
            sftp = getConnect("zhixin.asiainfo.com", 22, null, null);
            download("https://zhixin.asiainfo.com/gitlab/wupf/pdmcompare/repository/archive.zip?ref=master/wupf/jpfapp",
                    "jpfapp.zip", "G:\\test\\jpfapp.zip", sftp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章