Android FTP Server Upload File Introduction of Code Detailed Explanation

  • 2021-12-04 11:22:04
  • OfStack

1. Preface

During development, you will encounter the need to upload files to the FTP server. First, you must import
commons-net-3. 3. jar then uses api to do the following:

Ftp related code


import android.util.Log;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.FileInputStream;

public class FTPClientUtils {

 private static final String TAG = "MainActivity";
 private FTPClient ftpClient = null; // FTP Client 

 /**
 *  Connect to FTP Server 
 *
 * @param host ftp Server domain name 
 * @param username  Access user name 
 * @param password  Access password 
 * @param port  Port 
 * @return  Is the connection successful 
 */
 public boolean ftpConnect(String host, String username, String password, int port) {
 try {
  ftpClient = new FTPClient();
  ftpClient.connect(host,port);
  //  According to the returned status code, whether the link is established successfully or not is judged 
  if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
  boolean status = ftpClient.login(username, password);
  /*
   *  Set file transfer mode 
   *  Avoid 1 Some possible problems, here you must set the file transfer format. 
   *  Here we use BINARY_FILE_TYPE To transfer text, images, and compressed files. 
   */
  ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  ftpClient.enterLocalPassiveMode();
  return status;
  }
 } catch (Exception e) {
  e.printStackTrace();
 }
 return false;
 }

 /**
 *  Disconnect ftp Server connection 
 *
 * @return  Disconnect result 
 */
 public boolean ftpDisconnect() {
 //  Judge null pointer 
 if (ftpClient == null) {
  return true;
 }
 //  Disconnect ftp Server connection 
 try {
  ftpClient.logout();
  ftpClient.disconnect();
  return true;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return false;
 }

 /**
 * ftp  File upload 
 *
 * @param srcFilePath  Source file directory 
 * @param desFileName  File name 
 * @return  File upload results 
 */
 public boolean ftpUpload(String srcFilePath, String desFileName) {
 boolean status = false;
 try {
  FileInputStream srcFileStream = new FileInputStream(srcFilePath);
  status = ftpClient.storeFile(desFileName, srcFileStream);
  srcFileStream.close();
  return status;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return status;
 }

 /**
 * ftp  Change Directory 
 *
 * @param path  Changed path 
 * @return  Whether the change was successful 
 */
 public boolean ftpChangePath(String path) {
 boolean status = false;
 try {
  status = ftpClient.changeWorkingDirectory(path);
 } catch (Exception e) {
  e.printStackTrace();
 }
 return status;
 }
}

2. Call api


boolean isConnect = mFtpClient.ftpConnect(" Server host", " User name ", " Password ", 21);// The default port number is 21
  if (isConnect) {
  boolean isSuccessful = mFtpClient.ftpUpload("/sdcard/" + folderName + "/" + mPicturename, "/htdocs/pics/" + mPicturename);
  if (isSuccessful) {
   mFtpClient.ftpDisconnect();
  		// Upload succeeded 
  } else {
   // Upload failed 
  }
  } else {
  // Server connection failed 
  }

Appendix: I wrote FTP upload code when I was doing the project before:


package com.kandao.yunbell.videocall; 
 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.net.SocketException; 
 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPReply; 
 
import com.kandao.yunbell.common.SysApplication; 
 
import android.content.Context; 
import android.util.Log; 
 
public class MyUploadThread extends Thread { 
 private String fileName;//  File name  
 private String filePath;//  File local path  
 private String fileStoragePath;//  File server storage path  
 private String serverAddress;//  Server address  
 private String ftpUserName;// ftp Account number  
 private String ftpPassword;// ftp Password  
 private Context mContext; 
 public MyUploadThread() { 
 super(); 
 // TODO Auto-generated constructor stub 
 } 
 
 public MyUploadThread(Context mContext,String fileName, String filePath, 
  String fileStoragePath,String serverAddress,String ftpUserName,String ftpPassword) { 
 super(); 
 this.fileName = fileName; 
 this.filePath = filePath; 
 this.fileStoragePath = fileStoragePath; 
 this.serverAddress = serverAddress; 
 this.ftpUserName = ftpUserName; 
 this.ftpPassword = ftpPassword; 
 this.mContext=mContext; 
 } 
 
 @Override 
 public void run() { 
 super.run(); 
 try { 
  FileInputStream fis=null; 
  FTPClient ftpClient = new FTPClient(); 
  String[] idPort = serverAddress.split(":"); 
  ftpClient.connect(idPort[0], Integer.parseInt(idPort[1])); 
  int returnCode = ftpClient.getReplyCode(); 
  Log.i("caohai", "returnCode,upload:"+returnCode); 
  boolean loginResult = ftpClient.login(ftpUserName, ftpPassword); 
  Log.i("caohai", "loginResult:"+loginResult); 
  if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {//  If login is successful  
   
  //  Set up the upload directory  
   
  if (((SysApplication) mContext).getIsVideo()) { 
   ((SysApplication) mContext).setIsVideo(false); 
   boolean ff=ftpClient.changeWorkingDirectory(fileStoragePath + "/video/"); 
   Log.i("caohai", "ff:"+ff); 
  }else{ 
  boolean ee=ftpClient.changeWorkingDirectory(fileStoragePath + "/photo/"); 
  Log.i("caohai", "ee:"+ee); 
  } 
  ftpClient.setBufferSize(1024); 
  // ftpClient.setControlEncoding("iso-8859-1"); 
  // ftpClient.enterLocalPassiveMode(); 
  ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 
   fis = new FileInputStream(filePath + "/" 
   + fileName); 
   Log.i("caohai", "fileStoragePath00000:"+fileStoragePath); 
  String[] path = fileStoragePath.split("visitorRecord"); 
   
  boolean fs = ftpClient.storeFile(new String((path[1] 
   + "/photo/" + fileName).getBytes(), "iso-8859-1"), fis); 
  Log.i("caohai", "shifoushangchuanchenggong:"+fs); 
  fis.close(); 
  ftpClient.logout(); 
  //ftpClient.disconnect(); 
  } else {//  If login fails  
  ftpClient.disconnect(); 
  } 
 } catch (NumberFormatException e) { 
  // TODO Auto-generated catch block 
  e.printStackTrace(); 
 } catch (SocketException e) { 
  // TODO Auto-generated catch block 
  e.printStackTrace(); 
 } catch (FileNotFoundException e) { 
  // TODO Auto-generated catch block 
  e.printStackTrace(); 
 } catch (UnsupportedEncodingException e) { 
  // TODO Auto-generated catch block 
  e.printStackTrace(); 
 } catch (IOException e) { 
  // TODO Auto-generated catch block 
  e.printStackTrace(); 
 } 
 
 } 
} 

Summarize


Related articles: