歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程之FTP文件上傳

Android開發教程之FTP文件上傳

日期:2017/3/1 10:28:01   编辑:Linux編程

Android客戶端實現FTP文件(包括圖片)上傳應該沒什麼難度。寫下來就了為了記錄一下,望能幫到新手。

需要用到 commons-net-3.0.1.jar,附上jar包。

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /2012年資料/2月/29日/Android開發教程之FTP文件上傳/

直接上代碼:

  1. /**
  2. * 通過ftp上傳文件
  3. * @param url ftp服務器地址 如: 192.168.1.110
  4. * @param port 端口如 : 21
  5. * @param username 登錄名
  6. * @param password 密碼
  7. * @param remotePath 上到ftp服務器的磁盤路徑
  8. * @param fileNamePath 要上傳的文件路徑
  9. * @param fileName 要上傳的文件名
  10. * @return
  11. */
  12. public String ftpUpload(String url, String port, String username,String password, String remotePath, String fileNamePath,String fileName) {
  13. FTPClient ftpClient = new FTPClient();
  14. FileInputStream fis = null;
  15. String returnMessage = "0";
  16. try {
  17. ftpClient.connect(url, Integer.parseInt(port));
  18. boolean loginResult = ftpClient.login(username, password);
  19. int returnCode = ftpClient.getReplyCode();
  20. if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登錄成功
  21. ftpClient.makeDirectory(remotePath);
  22. // 設置上傳目錄
  23. ftpClient.changeWorkingDirectory(remotePath);
  24. ftpClient.setBufferSize(1024);
  25. ftpClient.setControlEncoding("UTF-8");
  26. ftpClient.enterLocalPassiveMode();
  27. fis = new FileInputStream(fileNamePath + fileName);
  28. ftpClient.storeFile(fileName, fis);
  29. returnMessage = "1"; //上傳成功
  30. } else {// 如果登錄失敗
  31. returnMessage = "0";
  32. }
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. throw new RuntimeException("FTP客戶端出錯!", e);
  36. } finally {
  37. //IOUtils.closeQuietly(fis);
  38. try {
  39. ftpClient.disconnect();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. throw new RuntimeException("關閉FTP連接發生異常!", e);
  43. }
  44. }
  45. return returnMessage;
  46. }
Copyright © Linux教程網 All Rights Reserved