Java Code Examples for org.apache.commons.net.ftp.ftpclient#connect()

The following examples show how to use org.apache.commons.net.ftp.ftpclient#connect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FTPClientFactory.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
public PooledObject<FTPClient> makeObject() throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.setConnectTimeout(config.getClientTimeout());
    ftpClient.connect(config.getHost(), config.getPort());
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        logger.warn("FTPServer refused connection");
        return null;
    }
    boolean result = ftpClient.login(config.getUsername(), config.getPassword());
    if (!result) {
        throw new ConnectException("ftp登陆失败:" + config.getUsername() + "/password:" + config.getPassword() + "@" + config.getHost());
    }
    ftpClient.setFileType(config.getTransferFileType());
    ftpClient.setBufferSize(1024);
    ftpClient.setControlEncoding(config.getEncoding());
    if (config.isPassiveMode()) {
        ftpClient.enterLocalPassiveMode();
    }
    return new DefaultPooledObject<>(ftpClient);

}
 
Example 2
Source File: FtpHelper.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Connect.
 *
 * @throws Exception the exception
 */
@Override
public void connect() throws Exception {
	try {
		ftpClient = new FTPClient();
		ftpClient.connect(host, port);
		if (usePassiveMode) {
			ftpClient.enterLocalPassiveMode();
		}
		if (!ftpClient.login(user, password)) {
			ftpClient.logout();
			throw new Exception("Authentication failed");
           }
	} catch (Exception e) {
		close();
		throw new Exception("Connection failed");
	}
}
 
Example 3
Source File: Ftp.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
private FTPClient getClient() throws SocketException, IOException {
	FTPClient ftp = new FTPClient();
	ftp.addProtocolCommandListener(new PrintCommandListener(
			new PrintWriter(System.out)));
	ftp.setDefaultPort(getPort());
	ftp.connect(getIp());
	int reply = ftp.getReplyCode();
	if (!FTPReply.isPositiveCompletion(reply)) {
		log.warn("FTP server refused connection: {}", getIp());
		ftp.disconnect();
		return null;
	}
	if (!ftp.login(getUsername(), getPassword())) {
		log.warn("FTP server refused login: {}, user: {}", getIp(),
				getUsername());
		ftp.logout();
		ftp.disconnect();
		return null;
	}
	ftp.setControlEncoding(getEncoding());
	ftp.setFileType(FTP.BINARY_FILE_TYPE);
	ftp.enterLocalPassiveMode();
	return ftp;
}
 
Example 4
Source File: FtpConnection.java    From xian with Apache License 2.0 6 votes vote down vote up
FTPClient connect(String path, String addr, int port, String username, String password) throws Exception {
    FTPClient ftp = new FTPClient();
    int reply;
    ftp.connect(addr, port);
    ftp.login(username, password);
    ftp.configure(new FTPClientConfig(ftp.getSystemType()));
    ftp.setControlEncoding("UTF-8");
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return null;
    }
    ftp.changeWorkingDirectory(path);
    return ftp;
}
 
Example 5
Source File: BugReportSenderFtp.java    From YalpStore with GNU General Public License v2.0 6 votes vote down vote up
private boolean uploadAll() {
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(FTP_HOST, FTP_PORT);
        if (!ftpClient.login(FTP_USER, FTP_PASSWORD)) {
            return false;
        }
        String dirName = getDirName();
        ftpClient.makeDirectory(dirName);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
        ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
        boolean result = true;
        for (File file: files) {
            result &= upload(ftpClient, file, dirName + "/" + file.getName());
        }
        return result;
    } catch (IOException e) {
        Log.e(BugReportSenderFtp.class.getSimpleName(), "FTP network error: " + e.getMessage());
    } finally {
        closeSilently(ftpClient);
    }
    return false;
}
 
Example 6
Source File: FtpFileUtil.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
/**
 * Connect and login on given FTP server with provided credentials.
 * @param hostName the FTP server host name to connect
 * @param port the port to connect
 * @param userName the user name
 * @param password the password
 */
public static void connectAndLoginOnFTPServer(FTPClient ftpClient,
        String hostName, Integer port, String userName, String password) {
    try {
        if (port != null && port.intValue() > 0) {
            ftpClient.connect(hostName, port);
        } else {
            ftpClient.connect(hostName);
        }
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            throw new IOException(String.format("FTP server '%s' refused connection.", hostName));
        }

        // try to login
        if (!ftpClient.login(userName, password)) {
            throw new IOException(String.format("Unable to login to FTP server '%s'.", hostName));
        }
    } catch (IOException ex) {
        throw new RuntimeException(
                String.format("Unable to connect and login to FTP server '%s'. Cause: ", hostName), ex);
    }
}
 
Example 7
Source File: FtpUtil.java    From SSM with Apache License 2.0 6 votes vote down vote up
public static boolean uploadPicture(String FTP_HOSTNAME,int FTP_PORT,String FTP_USERNAME,String FTP_PASSWORD,String FTP_REMOTE_PATH,String picName,InputStream fileInputStream)throws IOException {
    //创建一个FtpClient
    FTPClient ftpClient = new FTPClient();
    //连接的ip和端口号
    ftpClient.connect(FTP_HOSTNAME,FTP_PORT);
    //登陆的用户名和密码
    ftpClient.login(FTP_USERNAME,FTP_PASSWORD);
    //将文件转换成输入流
    //修改文件的存放地址
    ftpClient.changeWorkingDirectory(FTP_REMOTE_PATH);
    //设置文件的上传格式
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    //将我们的文件流以什么名字存放
    boolean result = ftpClient.storeFile(picName,fileInputStream);
    //退出
    ftpClient.logout();
    return result;
}
 
Example 8
Source File: FtpUtil.java    From learning-taotaoMall with MIT License 5 votes vote down vote up
/** 
 * Description: 从FTP服务器下载文件 
 * @param host FTP服务器hostname 
 * @param port FTP服务器端口 
 * @param username FTP登录账号 
 * @param password FTP登录密码 
 * @param remotePath FTP服务器上的相对路径 
 * @param fileName 要下载的文件名 
 * @param localPath 下载后保存到本地的路径 
 * @return 
 */
public static boolean downloadFile(String host, int port, String username, String password, String remotePath, String fileName, String localPath) {
	boolean result = false;
	FTPClient ftp = new FTPClient();
	try {
		int reply;
		ftp.connect(host, port);
		// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
		ftp.login(username, password);// 登录
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return result;
		}
		ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
		FTPFile[] fs = ftp.listFiles();
		for (FTPFile ff : fs) {
			if (ff.getName().equals(fileName)) {
				File localFile = new File(localPath + "/" + ff.getName());

				OutputStream is = new FileOutputStream(localFile);
				ftp.retrieveFile(ff.getName(), is);
				is.close();
			}
		}

		ftp.logout();
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
			}
		}
	}
	return result;
}
 
Example 9
Source File: FTPUploader.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
private FTPClient getFTPClient(final String ftpServer, final String username, final String password)
        throws Exception {
    final FTPClient ftpClient = new FTPClient();
    ftpClient.connect(ftpServer);
    ftpClient.login(username, password);
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.enterLocalPassiveMode();
    return ftpClient;
}
 
Example 10
Source File: FTPUploader.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
protected FTPClient getFTPClient(final String ftpServer, final String username, final String password)
        throws Exception {
    final FTPClient ftpClient = new FTPClient();
    ftpClient.connect(ftpServer);
    ftpClient.login(username, password);
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.enterLocalPassiveMode();
    return ftpClient;
}
 
Example 11
Source File: Utils.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Uploads a file to an Azure web app.
 * @param profile the publishing profile for the web app.
 * @param fileName the name of the file on server
 * @param file the local file
 */
public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "./site/wwwroot/webapps";
    if (fileName.contains("/")) {
        int lastslash = fileName.lastIndexOf('/');
        path = path + "/" + fileName.substring(0, lastslash);
        fileName = fileName.substring(lastslash + 1);
    }
    try {
        ftpClient.connect(server);
        ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        for (String segment : path.split("/")) {
            if (!ftpClient.changeWorkingDirectory(segment)) {
                ftpClient.makeDirectory(segment);
                ftpClient.changeWorkingDirectory(segment);
            }
        }
        ftpClient.storeFile(fileName, file);
        ftpClient.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 12
Source File: Utils.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Uploads a file to an Azure function app.
 * @param profile the publishing profile for the web app.
 * @param fileName the name of the file on server
 * @param file the local file
 */
public static void uploadFileToFunctionApp(PublishingProfile profile, String fileName, InputStream file) {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "site/wwwroot";
    if (fileName.contains("/")) {
        int lastslash = fileName.lastIndexOf('/');
        path = path + "/" + fileName.substring(0, lastslash);
        fileName = fileName.substring(lastslash + 1);
    }
    try {
        ftpClient.connect(server);
        ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
        ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
        for (String segment : path.split("/")) {
            if (!ftpClient.changeWorkingDirectory(segment)) {
                ftpClient.makeDirectory(segment);
                ftpClient.changeWorkingDirectory(segment);
            }
        }
        ftpClient.storeFile(fileName, file);
        ftpClient.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 13
Source File: FTPUtil.java    From mmall20180107 with Apache License 2.0 5 votes vote down vote up
private boolean connectServer(String ip,int port,String user,String pwd){

        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user,pwd);
        } catch (IOException e) {
            logger.error("连接FTP服务器异常",e);
        }
        return isSuccess;
    }
 
Example 14
Source File: FTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected FTPClient connect(URI uri) throws IOException {
		FTPClient ftp = new FTPClient();
//		FTPClientConfig config = new FTPClientConfig();
//		config.setServerTimeZoneId("GMT+0");
//		ftp.configure(config);
		ftp.setListHiddenFiles(true);
		UserInfo userInfo = UserInfo.fromURI(uri);
		try {
			int port = uri.getPort();
			if (port < 0) {
				port = 21;
			}
			ftp.connect(uri.getHost(), port);
			if (!ftp.login(userInfo.getUser(), userInfo.getPassword())) {
	            ftp.logout();
	            throw new IOException(FileOperationMessages.getString("FTPOperationHandler.authentication_failed")); //$NON-NLS-1$
	        }
			ftp.enterLocalPassiveMode();
			
			int reply = ftp.getReplyCode();
	        if (!FTPReply.isPositiveCompletion(reply)) {
	        	throw new IOException(FileOperationMessages.getString("FTPOperationHandler.connection_failed")); //$NON-NLS-1$
	        }
	        return ftp;
		} catch (IOException ioe) {
			disconnect(ftp);
			throw new IOException(FileOperationMessages.getString("FTPOperationHandler.connection_failed"), ioe); //$NON-NLS-1$
		}
	}
 
Example 15
Source File: FtpUtils.java    From kkFileView with Apache License 2.0 5 votes vote down vote up
public static FTPClient connect(String host, int port, String username, String password, String controlEncoding) throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(host, port);
    if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
        ftpClient.login(username, password);
    }
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
    }
    ftpClient.setControlEncoding(controlEncoding);
    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    return ftpClient;
}
 
Example 16
Source File: FTPUtil.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
private void initFTPClient(){
    try{
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        ftpClient.connect(hostName,port);
        ftpClient.login(userName,password);
    }catch (Exception e){
        log.error("初始化FTP失败",e);
    }
}
 
Example 17
Source File: FtpCheck.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
    if (args.length < 3) {
        throw new IllegalArgumentException("Usage: FtpCheck user pass host dir");
    }
    final String user = args[0];
    final String pass = args[1];
    final String host = args[2];
    String dir = null;
    if (args.length == 4) {
        dir = args[3];
    }

    final FTPClient client = new FTPClient();
    client.connect(host);
    final int reply = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new IllegalArgumentException("cant connect: " + reply);
    }
    if (!client.login(user, pass)) {
        throw new IllegalArgumentException("login failed");
    }
    client.enterLocalPassiveMode();

    final OutputStream os = client.storeFileStream(dir + "/test.txt");
    if (os == null) {
        throw new IllegalStateException(client.getReplyString());
    }
    os.write("test".getBytes(Charset.defaultCharset()));
    os.close();
    client.completePendingCommand();

    if (dir != null && !client.changeWorkingDirectory(dir)) {
        throw new IllegalArgumentException("change dir to '" + dir + "' failed");
    }

    System.err.println("System: " + client.getSystemType());

    final FTPFile[] files = client.listFiles();
    for (int i = 0; i < files.length; i++) {
        final FTPFile file = files[i];
        if (file == null) {
            System.err.println("#" + i + ": " + null);
        } else {
            System.err.println("#" + i + ": " + file.getRawListing());
            System.err.println("#" + i + ": " + file.toString());
            System.err.println("\t name:" + file.getName() + " type:" + file.getType());
        }
    }
    client.disconnect();
}
 
Example 18
Source File: CfdaServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @return
 * @throws IOException
 */
public SortedMap<String, CFDA> getGovCodes() throws IOException {
    Calendar calendar = dateTimeService.getCurrentCalendar();
    SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>();

    // ftp://ftp.cfda.gov/programs09187.csv
    String govURL = parameterService.getParameterValueAsString(CfdaBatchStep.class, KFSConstants.SOURCE_URL_PARAMETER);
    String fileName = StringUtils.substringAfterLast(govURL, "/");
    govURL = StringUtils.substringBeforeLast(govURL, "/");
    if (StringUtils.contains(govURL, "ftp://")) {
        govURL = StringUtils.remove(govURL, "ftp://");
    }

    // need to pull off the '20' in 2009
    String year = "" + calendar.get(Calendar.YEAR);
    year = year.substring(2, 4);
    fileName = fileName + year;

    // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday"
    fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1);
    fileName = fileName + ".csv";

    LOG.info("Getting government file: " + fileName + " for update");

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(govURL);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            LOG.error("FTP connection to server not established.");
            throw new IOException("FTP connection to server not established.");
        }

        boolean isLoggedIn = ftp.login("anonymous", "");
        if (!isLoggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

        LOG.info("Successfully connected and logged in");
        ftp.enterLocalPassiveMode();
        inputStream = ftp.retrieveFileStream(fileName);
        if (inputStream != null) {
            LOG.info("reading input stream");
            InputStreamReader screenReader = new InputStreamReader(inputStream);
            BufferedReader screen = new BufferedReader(screenReader);

            CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1);
            List<String[]> lines = csvReader.readAll();
            for (String[] line : lines) {
                String title = line[0];
                String number = line[1];

                CFDA cfda = new CFDA();
                cfda.setCfdaNumber(number);
                cfda.setCfdaProgramTitleName(title);

                govMap.put(number, cfda);
            }
        }

        ftp.logout();
        ftp.disconnect();
    }
    finally {
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }

    return govMap;
}
 
Example 19
Source File: DownloadFileFromFtpToTable.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**
 * 下载文件并且存至tfs文件系统
 * 
 * @param remoteFileNameTmp
 * @param
 * @return
 */
private Map downLoadFileToTable(String remoteFileNameTmp, FTPClientTemplate ftpClientTemplate, Map ftpItemConfigInfo) {
	Map resultInfo = new HashMap();
	String tfsReturnFileName = null;
	long block = 10 * 1024;// 默认
	if (ftpClientTemplate == null) {
		resultInfo.put("SAVE_FILE_FLAG", "E");
		return resultInfo;
	}
	String localPathName = ftpItemConfigInfo.get("localPath").toString().endsWith("/") ? ftpItemConfigInfo.get("localPath").toString()
			+ ftpItemConfigInfo.get("newFileName").toString() : ftpItemConfigInfo.get("localPath").toString() + "/" + ftpItemConfigInfo.get("newFileName").toString();
	ftpItemConfigInfo.put("localfilename", localPathName);// 本地带路径的文件名回写,后面读文件时使用
	try {
		File file = new File(localPathName);
		RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");// 建立随机访问
		FTPClient ftpClient = new FTPClient();
		ftpClient.connect(ftpClientTemplate.getHost(), ftpClientTemplate.getPort());
		if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			if (!ftpClient.login(ftpClientTemplate.getUsername(), ftpClientTemplate.getPassword())) {
				resultInfo.put("SAVE_FILE_FLAG", "E");
				resultInfo.put("remark", "登录失败,用户名【" + ftpClientTemplate.getUsername() + "】密码【" + ftpClientTemplate.getPassword() + "】");
				return resultInfo;
			}
		}
		ftpClient.setControlEncoding("UTF-8");
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 二进制
		ftpClient.enterLocalPassiveMode(); // 被动模式
		ftpClient.sendCommand("PASV");
		ftpClient.sendCommand("SIZE " + remoteFileNameTmp + "\r\n");
		String replystr = ftpClient.getReplyString();
		String[] replystrL = replystr.split(" ");
		long filelen = 0;
		if (Integer.valueOf(replystrL[0]) == 213) {
			filelen = Long.valueOf(replystrL[1].trim());
		} else {
			resultInfo.put("SAVE_FILE_FLAG", "E");
			resultInfo.put("remark", "无法获取要下载的文件的大小!");
			return resultInfo;
		}
		accessFile.setLength(filelen);
		accessFile.close();
		ftpClient.disconnect();

		int tnum = Integer.valueOf(ftpItemConfigInfo.get("TNUM").toString());
		block = (filelen + tnum - 1) / tnum;// 每个线程下载的快大小
		ThreadPoolExecutor cachedThreadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		List<Future<Map>> threadR = new ArrayList<Future<Map>>();
		for (int i = 0; i < tnum; i++) {
			logger.debug("发起线程:" + i);
			// 保存线程日志
			ftpItemConfigInfo.put("threadrunstate", "R");
			ftpItemConfigInfo.put("remark", "开始下载文件");
			ftpItemConfigInfo.put("data", "文件名:" + remoteFileNameTmp);
			long start = i * block;
			long end = (i + 1) * block - 1;
			ftpItemConfigInfo.put("begin", start);
			ftpItemConfigInfo.put("end", end);
			saveTaskLogDetail(ftpItemConfigInfo);
			Map para = new HashMap();
			para.putAll(ftpItemConfigInfo);
			para.put("serverfilename", remoteFileNameTmp);
			para.put("filelength", filelen);
			para.put("tnum", i + 0);
			para.put("threadDownSize", block);
			para.put("transferflag", FTPClientTemplate.TransferType.download);
			FTPClientTemplate dumpThread = new FTPClientTemplate(para);
			Future<Map> runresult = cachedThreadPool.submit(dumpThread);
			threadR.add(runresult);
		}

		do {
			// 等待下载完成
			Thread.sleep(1000);
		} while (cachedThreadPool.getCompletedTaskCount() < threadR.size());

		saveDownFileData(ftpItemConfigInfo);
		// 下载已经完成,多线程保存数据至表中

	} catch (Exception e) {
		// TODO Auto-generated catch block
		logger.error("保存文件失败:", e);
		resultInfo.put("SAVE_FILE_FLAG", "E");
		resultInfo.put("remark", "保存文件失败:" + e);
		return resultInfo;
	}
	resultInfo.put("SAVE_FILE_FLAG", "S");
	return resultInfo;

}
 
Example 20
Source File: FtpUtil.java    From learning-taotaoMall with MIT License 4 votes vote down vote up
/** 
 * Description: 向FTP服务器上传文件 
 * @param host FTP服务器hostname 
 * @param port FTP服务器端口 
 * @param username FTP登录账号 
 * @param password FTP登录密码 
 * @param basePath FTP服务器基础目录
 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
 * @param filename 上传到FTP服务器上的文件名 
 * @param input 输入流 
 * @return 成功返回true,否则返回false 
 */
public static boolean uploadFile(String host, int port, String username, String password, String basePath, String filePath, String filename,
		InputStream input) {
	boolean result = false;
	FTPClient ftp = new FTPClient();
	try {
		int reply;
		ftp.connect(host, port);// 连接FTP服务器
		// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
		ftp.login(username, password);// 登录
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return result;
		}
		//切换到上传目录
		if (!ftp.changeWorkingDirectory(basePath + filePath)) {
			//如果目录不存在创建目录
			String[] dirs = filePath.split("/");
			String tempPath = basePath;
			for (String dir : dirs) {
				if (null == dir || "".equals(dir))
					continue;
				tempPath += "/" + dir;
				if (!ftp.changeWorkingDirectory(tempPath)) {
					if (!ftp.makeDirectory(tempPath)) {
						return result;
					} else {
						ftp.changeWorkingDirectory(tempPath);
					}
				}
			}
		}
		//设置上传文件的类型为二进制类型
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
		//上传文件
		if (!ftp.storeFile(filename, input)) {
			return result;
		}
		input.close();
		ftp.logout();
		result = true;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (ftp.isConnected()) {
			try {
				ftp.disconnect();
			} catch (IOException ioe) {
			}
		}
	}
	return result;
}