Android FTP服务器上传文件攻略(代码详解)

2020-10-16 10:03:26 浏览数 (1)

1.前言

在开发中,会遇到向FTP服务器上传文件的需求,首先要导入 commons-net-3.3.jar 然后利用api进行相关操作,具体功能如下:

Ftp相关代码

代码语言:javascript复制
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客户端

 /**
 * 连接到FTP服务器
 *
 * @param host ftp服务器域名
 * @param username 访问用户名
 * @param password 访问密码
 * @param port 端口
 * @return 是否连接成功
 */
 public boolean ftpConnect(String host, String username, String password, int port) {
 try {
  ftpClient = new FTPClient();
  ftpClient.connect(host,port);
  // 根据返回的状态码,判断链接是否建立成功
  if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
  boolean status = ftpClient.login(username, password);
  /*
   * 设置文件传输模式
   * 避免一些可能会出现的问题,在这里必须要设定文件的传输格式。
   * 在这里我们使用BINARY_FILE_TYPE来传输文本、图像和压缩文件。
   */
  ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  ftpClient.enterLocalPassiveMode();
  return status;
  }
 } catch (Exception e) {
  e.printStackTrace();
 }
 return false;
 }

 /**
 * 断开ftp服务器连接
 *
 * @return 断开结果
 */
 public boolean ftpDisconnect() {
 // 判断空指针
 if (ftpClient == null) {
  return true;
 }
 // 断开ftp服务器连接
 try {
  ftpClient.logout();
  ftpClient.disconnect();
  return true;
 } catch (Exception e) {
  e.printStackTrace();
 }
 return false;
 }

 /**
 * ftp 文件上传
 *
 * @param srcFilePath 源文件目录
 * @param desFileName 文件名称
 * @return 文件上传结果
 */
 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 更改目录
 *
 * @param path 更改的路径
 * @return 更改是否成功
 */
 public boolean ftpChangePath(String path) {
 boolean status = false;
 try {
  status = ftpClient.changeWorkingDirectory(path);
 } catch (Exception e) {
  e.printStackTrace();
 }
 return status;
 }
}

2.调用api

代码语言:javascript复制
boolean isConnect = mFtpClient.ftpConnect("服务器host", "用户名", "密码", 21);//默认端口号是21
  if (isConnect) {
  boolean isSuccessful = mFtpClient.ftpUpload("/sdcard/"   folderName   "/"   mPicturename, "/htdocs/pics/"   mPicturename);
  if (isSuccessful) {
   mFtpClient.ftpDisconnect();
  		//上传成功
  } else {
   //上传失败
  }
  } else {
  //服务器连接失败
  }

附录:自己之前做项目的时候写过的FTP上传代码:

代码语言:javascript复制
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;// 文件名字 
private String filePath;// 文件本地路径 
private String fileStoragePath;// 文件服务器存储路径 
private String serverAddress;// 服务器地址 
private String ftpUserName;// ftp账号 
private String ftpPassword;// ftp密码 
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 (((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 {// 如果登录失败 
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(); 
} 
} 
} 

总结

到此这篇关于Android FTP服务器上传文件攻略的文章就介绍到这了,更多相关Android FTP服务器上传内容请搜索ZaLou.Cn以前的文章或继续浏览下面的相关文章希望大家以后多多支持ZaLou.Cn!

0 人点赞