運用 http://commons.apache.org/net/ 提供的API 可以輕鬆的完成 ftp 檔案上傳, 該API提供相當多種協定可使用, 如 FTP/FTPS, FTP over HTTP (experimental), NNTP, SMTP(S), POP3(S), IMAP(S), Telnet, TFTP, Finger, Whois, rexec/rcmd/rlogin, Time (rdate) and Daytime, Echo, Discard, NTP/SNTP 等
檔案上傳方式
檔案上傳方式
private FTPClient ftp; // public void ftpFile() { if (connect("192.168.0.1", 21)) { try { if (login("test", "test")) { boolean result = false; // FileInputStream srcFileStream = new FileInputStream("/sdcard/file.txt"); if (ftp.storeFile("file.txt", srcFileStream)) { //上傳完成 } else { //上傳失敗 } srcFileStream.close(); } else { //登入失敗 } } catch (Exception e) { e.printStackTrace(); //遠端連線失敗 } } disconnect(); } // 遠端連線 public boolean connect(String host, int port) { try { ftp = new FTPClient(); ftp.connect(host, port); //check the reply code, if positive mean connection success return FTPReply.isPositiveCompletion(ftp.getReplyCode()); } catch (Exception e) { Log.d(TAG, "Could not connect to host " + host); } return false; } // 斷線 public boolean disconnect() { try { ftp.logout(); ftp.disconnect(); return true; } catch (Exception e) { Log.d(TAG, "Error occurred while disconnecting from ftp server"); } return false; } // 登入 public boolean login(String username, String password) { try { if (ftp.login(username, password)) { ftp.setFileType(FTP.BINARY_FILE_TYPE);// 此模式可以傳送各種格式檔案 ftp.enterLocalPassiveMode(); return true; } } catch (Exception e) { Log.d(TAG, "Could not login"); } return false; }