Android FTP上传文件

前言

Android 上用 FTP上传文件 通常可以用以下的这两个Jar

  • commons-net
  • ftp4j

我这里就用第一种方式
第二种请参考通过FTP4J 实现FTP各种操作

使用方式

引用

1
2
//FTP
compile group: 'commons-net', name: 'commons-net', version: '3.5'

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class UploadTask extends AsyncTask<String, Object, Integer> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Integer doInBackground(String... params) {
String ftp_url = "192.168.1.100";
String ftp_name = "name";
String ftp_pwd = "pwd";

String fileName = params[0];

String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String filePath = basePath + File.separator + "caiyun" + File.separator + fileName;
String remotePath = File.separator + fileName.substring(0, 2);
FTPClient ftpClient = new FTPClient();
FileInputStream fis;
int returnMessage = 0;
try {
ftpClient.connect(ftp_url, 21);
boolean loginResult = ftpClient.login(ftp_name, ftp_pwd);
int returnCode = ftpClient.getReplyCode();
if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功
ftpClient.makeDirectory(remotePath);
// 设置上传目录
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
fis = new FileInputStream(filePath);

//不计算进度条
//ftpClient.storeFile(fileName, fis);

//计算进度条
int n = -1;
long pContentLength = fis.available();
long trans = 0;
int bufferSize = ftpClient.getBufferSize();
byte[] buffer = new byte[bufferSize];
OutputStream outputstream = ftpClient.storeFileStream(new String(fileName.getBytes("utf-8"), "iso-8859-1"));
while ((n = fis.read(buffer)) != -1) {
outputstream.write(buffer, 0, n);
trans += n;
//trans已传输字节 pContentLength总字节
publishProgress(trans, pContentLength);
}
fis.close();
outputstream.flush();
outputstream.close();

returnMessage = 1; //上传成功
} else {// 如果登录失败
returnMessage = 0;
}


} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
return returnMessage;
}

@Override
protected void onPostExecute(Integer result) {
if (result == 1) {
//上传成功后调用
}

}

@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
//获取进度
long trans = (long) values[0];
long pContentLength = (long) values[1];
int progress = (int) (trans * 100 / pContentLength);

}
}

调用方式

1
new UploadTask("123.jpg").execute();