上传文件到Ftp服务器FtpClientFile工具类

public class FtpClientFile {
    /**
     * log
     */
    private static final Logger log = LoggerFactory.getLogger(FtpClientFile.class);
    private static final String hostname = "" ;//FTP IP
    private static final int port = ;//FTP 端口号
    private static final String username = "";//FTP 登录账号
    private static final String password = ""; //FTP 登录密码
    private static final String pathname = "";//FTP 工作路径



    /**
     * 上传文件(可供Action/Controller层使用)
     * @param fileName 上传到FTP服务器后的文件名称
     * @param inputStream 输入文件流
     * @return
     */
    public static boolean uploadFile(String fileName, FileInputStream inputStream){

        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        //设置超时
        ftpClient.setConnectTimeout(60*60*1000);
        //设置编码
        ftpClient.setControlEncoding("UTF-8");
        try {
            //连接FTP服务器
            log.info("连接服务器");
            ftpClient.connect(hostname, port);
            //登录FTP服务器
            log.info("登录服务器");
            ftpClient.login(username, password);
            //是否成功登录FTP服务器
            int replyCode = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(replyCode)){
                log.error("登录服务器失败");
                return flag;
            }
           log.info("登录服务器成功");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //切换路径 创建路径
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.enterLocalPassiveMode();
            //设置缓冲
            ftpClient.setBufferSize(1024 * 1024 * 20);
            //保持连接
            ftpClient.setKeepAlive(true);
            boolean a = ftpClient.storeFile(new String(fileName.getBytes("utf-8"),"iso-8859-1"), inputStream);
            if(a){
                log.info("创建文件成功"+a);
                String fileName2 = fileName;
                boolean status = ftpClient.rename(fileName, fileName2);
                if(status)
                    log.info("修改文件名称成功"+status);
                inputStream.close();
                ftpClient.logout();
                flag = true;
            }else{
                flag = false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;

    }





}

 

上传文件到Ftp服务器FtpClientFile工具类

上一篇:JQuery基础


下一篇:浏览器中http请求