Upload files to ftp server through FTPClient

To realize uploading and downloading, FTPClient needs two jar packages, jakarta-oro-2.0.8.jar and commons-net-1.4.1.jar.

public boolean uploadFile(String filename,InputStream input){
		 boolean success = false;
		FTPClient client = new FTPClient();
		try {
			client.connect("ip address", port number);
			client.login("username", "password");
			int reply = client.getReplyCode ();
			if(!FTPReply.isPositiveCompletion(reply)){
				client.disconnect();
				return success;
			}
			client.enterLocalPassiveMode();
			//client.changeWorkingDirectory(pathname);
			FTPFile[] files = client.listFiles();
			System.out.println(files.length);
			client.storeFile(filename, input);
			input.close();
			client.logout();
			success = true;
		} catch (SocketException e) {
			e.printStackTrace ();
		} catch (IOException e) {
			e.printStackTrace ();
		}finally{
			if (client.isConnected()) {
				try {
					client.disconnect();
				} catch (IOException e) {
					e.printStackTrace ();
				}
			}
		}
		return success;
	}  

    We add the sentence client.enterLocalPassiveMode(); before client.listFiles(); to prevent the program from "stuck" when executing listFiles().

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326444245&siteId=291194637