java实现FTP服务上传下载

   ftp文件的上传与下载

@Controller
@RequestMapping("/ftp")
public class UploadFileToFtpController {

    private static Logger log = LoggerFactory.getLogger(UploadFileToFtpController.class);

    private ChannelSftp sftp;

    private Session session;
    /** FTP 登录用户名*/
    private String username;
    /** FTP 登录密码*/
    private String password;
    /** 私钥 */
    private String privateKey;
    /** FTP 服务器地址IP地址*/
    private String host;
    /** FTP 端口*/
    private int port;

    public UploadFileToFtpController(){}

    /**
     * 构造基于密码认证的sftp对象
     * @param username
     * @param password
     * @param host
     * @param port
     */
    public UploadFileToFtpController(String username, String password, String host, int port) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }



    @RequestMapping("/upload")
    public  Map<String,Object> uploadFile(String dir ,String fileName ){
        String sourceFilePath =  Config.getString(BhConstant.BAIHANG_SOURCE_FILE_PATH)+File.separator + dir + File.separator ;
        String sourceFile = sourceFilePath + fileName;
        String ftpHost =  Config.getString(BhConstant.BAIHANG_FTP_URL);
        int ftpPort = Integer.valueOf( Config.getString(BhConstant.BAIHANG_FTP_PORT));
        String ftpUserName = Config.getString(BhConstant.BAIHANG_FTP_USERNAME);
        String ftpPass = Config.getString(BhConstant.BAIHANG_FTP_PASSWORD);
        String ftpFilePath = Config.getString(BhConstant.BAIHANG_TARGET_FILE_PATH);
        Map<String, Object> map = Maps.newHashMap();
        try {

            UploadFileToFtpController sftp = new UploadFileToFtpController(ftpUserName, ftpPass, ftpHost, ftpPort);
            log.info("开始连接ftp...ftpHost={},ftpPort={},ftpUserName={},ftpPass={},ftpFilePath={}",ftpHost,ftpPort,ftpUserName,ftpPass,ftpFilePath);
            sftp.login();
            //byte[] buff = sftp.download("/opt", "start.sh");
            //System.out.println(Arrays.toString(buff));
            File file = new File(sourceFile);
            InputStream is = new FileInputStream(file);

            sftp.upload(ftpFilePath, fileName, is);

            log.info("文件上传成功.....................");
            sftp.logout();

            map.put("error",0);
            map.put("errorMsg","文件上传成功!");
        } catch (Exception e) {
            LogUtil.error(this,"uploadFile exception.", e);
            map.put("error",-1);
            map.put("errorMsg","调用异常");
        }finally {
            log.info("sftp通道关闭.........");
        }
        return  map;
    }


    @RequestMapping("/delete")
    public  Map<String,Object> deleteFile(String fileName ){
        //String sourceFilePath =  Config.getString(BhConstant.BAIHANG_SOURCE_FILE_PATH)+File.separator + dir + File.separator ;
        //String sourceFile = sourceFilePath + fileName;
        String ftpHost =  Config.getString(BhConstant.BAIHANG_FTP_URL);
        int ftpPort = Integer.valueOf( Config.getString(BhConstant.BAIHANG_FTP_PORT));
        String ftpUserName = Config.getString(BhConstant.BAIHANG_FTP_USERNAME);
        String ftpPass = Config.getString(BhConstant.BAIHANG_FTP_PASSWORD);
        String ftpFilePath = Config.getString(BhConstant.BAIHANG_TARGET_FILE_PATH);
        Map<String, Object> map = Maps.newHashMap();
        try {

            UploadFileToFtpController sftp = new UploadFileToFtpController(ftpUserName, ftpPass, ftpHost, ftpPort);
            log.info("开始连接ftp...ftpHost={},ftpPort={},ftpUserName={},ftpPass={},ftpFilePath={}",ftpHost,ftpPort,ftpUserName,ftpPass,ftpFilePath);
            sftp.login();
            delete(ftpFilePath,fileName);

            log.info("删除文件成功.....................");
            sftp.logout();

            map.put("error",0);
            map.put("errorMsg","");
        } catch (Exception e) {
            LogUtil.error(this,"uploadFile exception.", e);
            map.put("error",-1);
            map.put("errorMsg","调用异常");
        }finally {
            log.info("sftp通道关闭.........");
        }
        return  map;
    }

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

    /**
     * 连接sftp服务器
     *
     * @throws Exception
     */
    public void login(){
        try {
            JSch jsch = new JSch();
            if (privateKey != null) {
                jsch.addIdentity(privateKey);// 设置私钥
                log.info("sftp connect,path of private key file:{}" , privateKey);
            }
            log.info("sftp connect by host:{} username:{}",host,username);

            session = jsch.getSession(username, host, port);
            log.info("Session is build");
            if (password != null) {
                session.setPassword(password);
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);
            session.connect();
            log.info("Session is connected");

            Channel channel = session.openChannel("sftp");
            channel.connect();
            log.info("channel is connected");

            sftp = (ChannelSftp) channel;
            log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));
        } catch (JSchException e) {
            log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {}", new Object[]{host, port, e.getMessage()});
        }
    }

    /**
     * 关闭连接 server
     */
    public void logout(){
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
                log.info("sftp is closed already");
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
                log.info("sshSession is closed already");
            }
        }
    }

    /**
     * 将输入流的数据上传到sftp作为文件
     *
     * @param directory
     *            上传到该目录
     * @param sftpFileName
     *            sftp端文件名
     * @param input
     *            输入流
     * @throws SftpException
     * @throws Exception
     */
    public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{
        try {
            sftp.cd(directory);
        } catch (SftpException e) {
            log.warn("directory is not exist");
            sftp.mkdir(directory);
            sftp.cd(directory);
        }
        sftp.put(input, sftpFileName);
        log.info("file:{} is upload successful" , sftpFileName);
    }








你可能感兴趣的:(java)