Home

fangxiaogang

我可以!

Home About Github Email

2017-06-22
Ftp Android 客户端上传下载方案详解

由于一些原因,需要使用公司电脑的 ftp 服务器来实现上传和下载一些小文件,发现网上的一些资料不全或不可用或年代久远,故将源码分享出来,希望有所对新人有所帮助。


使用 ftp 服务器需要的参数有网址或ip、端口、用户名和密码。在项目中我使用的一个名为 的库,接下来只需三个 java 类即可实现上传、下载、删除。由于在项目中只需上传下载指定文件,所以暂时没有加入选择文件功能,如需要自行加入即可。在代码中该有的注释都有了,方法简洁明了。完整代码已经上至 Github


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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
public class FTP {
/**
* 服务器名.
*/
private String hostName;
/**
* 端口号
*/
private int serverPort;
/**
* 用户名.
*/
private String userName;
/**
* 密码.
*/
private String password;
/**
* FTP连接.
*/
private FTPClient ftpClient;
public FTP() {
//hostname的网址不需要加入ftp:// 直接输入网址即可
this.hostName = "www.socket.net.cn";
this.serverPort = 1001;//默认为21,这个可手动更改
this.userName = "";//账号
this.password = "";//密码
this.ftpClient = new FTPClient();
}
// -------------------------------------------------------文件上传方法------------------------------------------------
/**
* 上传单个文件.
*
* @param localFile
* 本地文件
* @param remotePath
* FTP目录
* @param listener
* 监听器
* @throws IOException
*/
public void uploadSingleFile(File singleFile, String remotePath,
UploadProgressListener listener) throws IOException {
// 上传之前初始化
this.uploadBeforeOperate(remotePath, listener);
boolean flag;
flag = uploadingSingle(singleFile, listener);
if (flag) {
listener.onUploadProgress(MainActivity.FTP_UPLOAD_SUCCESS, 0,
singleFile);
} else {
listener.onUploadProgress(MainActivity.FTP_UPLOAD_FAIL, 0,
singleFile);
}
// 上传完成之后关闭连接
this.uploadAfterOperate(listener);
}
/**
* 上传多个文件.
*
* @param localFile
* 本地文件
* @param remotePath
* FTP目录
* @param listener
* 监听器
* @throws IOException
*/
public void uploadMultiFile(LinkedList<File> fileList, String remotePath,
UploadProgressListener listener) throws IOException {
// 上传之前初始化
this.uploadBeforeOperate(remotePath, listener);
boolean flag;
for (File singleFile : fileList) {
flag = uploadingSingle(singleFile, listener);
if (flag) {
listener.onUploadProgress(MainActivity.FTP_UPLOAD_SUCCESS, 0,
singleFile);
} else {
listener.onUploadProgress(MainActivity.FTP_UPLOAD_FAIL, 0,
singleFile);
}
}
// 上传完成之后关闭连接
this.uploadAfterOperate(listener);
}
/**
* 上传单个文件.
*
* @param localFile
* 本地文件
* @return true上传成功, false上传失败
* @throws IOException
*/
private boolean uploadingSingle(File localFile,
UploadProgressListener listener) throws IOException {
boolean flag = true;
// 不带进度的方式
// // 创建输入流
// InputStream inputStream = new FileInputStream(localFile);
// // 上传单个文件
// flag = ftpClient.storeFile(localFile.getName(), inputStream);
// // 关闭文件流
// inputStream.close();
// 带有进度的方式
BufferedInputStream buffIn = new BufferedInputStream(
new FileInputStream(localFile));
ProgressInputStream progressInput = new ProgressInputStream(buffIn,
listener, localFile);
flag = ftpClient.storeFile(localFile.getName(), progressInput);
buffIn.close();
return flag;
}
/**
* 上传文件之前初始化相关参数
*
* @param remotePath
* FTP目录
* @param listener
* 监听器
* @throws IOException
*/
private void uploadBeforeOperate(String remotePath,
UploadProgressListener listener) throws IOException {
// 打开FTP服务
try {
this.openConnect();
listener.onUploadProgress(MainActivity.FTP_CONNECT_SUCCESSS, 0,
null);
} catch (IOException e1) {
e1.printStackTrace();
listener.onUploadProgress(MainActivity.FTP_CONNECT_FAIL, 0, null);
return;
}
// 设置模式
ftpClient.setFileTransferMode(org.apache.commons.net.ftp.FTP.STREAM_TRANSFER_MODE);
// FTP下创建文件夹
ftpClient.makeDirectory(remotePath);
// 改变FTP目录
ftpClient.changeWorkingDirectory(remotePath);
// 上传单个文件
}
/**
* 上传完成之后关闭连接
*
* @param listener
* @throws IOException
*/
private void uploadAfterOperate(UploadProgressListener listener)
throws IOException {
this.closeConnect();
listener.onUploadProgress(MainActivity.FTP_DISCONNECT_SUCCESS, 0, null);
}
// -------------------------------------------------------文件下载方法------------------------------------------------
/**
* 下载单个文件,可实现断点下载.
*
* @param serverPath
* Ftp目录及文件路径
* @param localPath
* 本地目录
* @param fileName
* 下载之后的文件名称
* @param listener
* 监听器
* @throws IOException
*/
public void downloadSingleFile(String serverPath, String localPath, String fileName, DownLoadProgressListener listener)
throws Exception {
// 打开FTP服务
try {
this.openConnect();
listener.onDownLoadProgress(MainActivity.FTP_CONNECT_SUCCESSS, 0, null);
} catch (IOException e1) {
e1.printStackTrace();
listener.onDownLoadProgress(MainActivity.FTP_CONNECT_FAIL, 0, null);
return;
}
// 先判断服务器文件是否存在
FTPFile[] files = ftpClient.listFiles(serverPath);
if (files.length == 0) {
listener.onDownLoadProgress(MainActivity.FTP_FILE_NOTEXISTS, 0, null);
return;
}
//创建本地文件夹
File mkFile = new File(localPath);
if (!mkFile.exists()) {
mkFile.mkdirs();
}
localPath = localPath + fileName;
// 接着判断下载的文件是否能断点下载
long serverSize = files[0].getSize(); // 获取远程文件的长度
File localFile = new File(localPath);
long localSize = 0;
if (localFile.exists()) {
localSize = localFile.length(); // 如果本地文件存在,获取本地文件的长度
if (localSize >= serverSize) {
File file = new File(localPath);
file.delete();
}
}
// 进度
long step = serverSize / 100;
long process = 0;
long currentSize = 0;
// 开始准备下载文件
OutputStream out = new FileOutputStream(localFile, true);
ftpClient.setRestartOffset(localSize);
InputStream input = ftpClient.retrieveFileStream(serverPath);
byte[] b = new byte[1024];
int length = 0;
while ((length = input.read(b)) != -1) {
out.write(b, 0, length);
currentSize = currentSize + length;
if (currentSize / step != process) {
process = currentSize / step;
if (process % 5 == 0) { //每隔%5的进度返回一次
listener.onDownLoadProgress(MainActivity.FTP_DOWN_LOADING, process, null);
}
}
}
out.flush();
out.close();
input.close();
// 此方法是来确保流处理完毕,如果没有此方法,可能会造成现程序死掉
if (ftpClient.completePendingCommand()) {
listener.onDownLoadProgress(MainActivity.FTP_DOWN_SUCCESS, 0, new File(localPath));
} else {
listener.onDownLoadProgress(MainActivity.FTP_DOWN_FAIL, 0, null);
}
// 下载完成之后关闭连接
this.closeConnect();
listener.onDownLoadProgress(MainActivity.FTP_DISCONNECT_SUCCESS, 0, null);
return;
}
// -------------------------------------------------------文件删除方法------------------------------------------------
/**
* 删除Ftp下的文件.
*
* @param serverPath
* Ftp目录及文件路径
* @param listener
* 监听器
* @throws IOException
*/
public void deleteSingleFile(String serverPath, DeleteFileProgressListener listener)
throws Exception {
// 打开FTP服务
try {
this.openConnect();
listener.onDeleteProgress(MainActivity.FTP_CONNECT_SUCCESSS);
} catch (IOException e1) {
e1.printStackTrace();
listener.onDeleteProgress(MainActivity.FTP_CONNECT_FAIL);
return;
}
// 先判断服务器文件是否存在
FTPFile[] files = ftpClient.listFiles(serverPath);
if (files.length == 0) {
listener.onDeleteProgress(MainActivity.FTP_FILE_NOTEXISTS);
return;
}
//进行删除操作
boolean flag = true;
flag = ftpClient.deleteFile(serverPath);
if (flag) {
listener.onDeleteProgress(MainActivity.FTP_DELETEFILE_SUCCESS);
} else {
listener.onDeleteProgress(MainActivity.FTP_DELETEFILE_FAIL);
}
// 删除完成之后关闭连接
this.closeConnect();
listener.onDeleteProgress(MainActivity.FTP_DISCONNECT_SUCCESS);
return;
}
// -------------------------------------------------------打开关闭连接------------------------------------------------
/**
* 打开FTP服务.
*
* @throws IOException
*/
public void openConnect() throws IOException {
ftpClient.setControlEncoding("UTF-8");
int reply; // 服务器响应值
// 连接至服务器
ftpClient.connect(hostName, serverPort);
// 获取响应值
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
// 断开连接
ftpClient.disconnect();
throw new IOException("connect fail: " + reply);
}
// 登录到服务器
ftpClient.login(userName, password);
// 获取响应值
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
// 断开连接
ftpClient.disconnect();
throw new IOException("connect fail: " + reply);
} else {
// 获取登录信息
FTPClientConfig config = new FTPClientConfig(ftpClient
.getSystemType().split(" ")[0]);
config.setServerLanguageCode("zh");
ftpClient.configure(config);
// 使用被动模式设为默认
ftpClient.enterLocalPassiveMode();
// 二进制文件支持
ftpClient
.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
}
}
/**
* 关闭FTP服务.
*
* @throws IOException
*/
public void closeConnect() throws IOException {
if (ftpClient != null) {
// 退出FTP
ftpClient.logout();
// 断开连接
ftpClient.disconnect();
}
}
// ---------------------------------------------------上传、下载、删除监听---------------------------------------------
/*
* 上传进度监听
*/
public interface UploadProgressListener {
public void onUploadProgress(String currentStep, long uploadSize, File file);
}
/*
* 下载进度监听
*/
public interface DownLoadProgressListener {
public void onDownLoadProgress(String currentStep, long downProcess, File file);
}
/*
* 文件删除监听
*/
public interface DeleteFileProgressListener {
public void onDeleteProgress(String currentStep);
}
}

fangxiaogang

scribble

Home About Github Email