fpclient 實(shí)現(xiàn)上傳文件到指定服務(wù)器,供大家參考,具體內(nèi)容如下
調(diào)用
1
2
|
fileinputstream in= new fileinputstream( new file(fileurl)); movefile( "10.3.3.**" , 21 , "username" , "password" , path, filename, in); |
方法
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
|
/** * description: 向ftp服務(wù)器上傳文件 * @param url ftp服務(wù)器hostname * @param port ftp服務(wù)器端口 * @param username ftp登錄賬號(hào) * @param password ftp登錄密碼 * @param path ftp服務(wù)器保存目錄 * @param filename 上傳到ftp服務(wù)器上的文件名 * @param input 輸入流 * @return 成功返回true,否則返回false */ public static boolean movefile(string url, int port,string username, string password, string path, string filename, inputstream input) { boolean success = false ; ftpclient ftp = new ftpclient(); try { int reply; ftp.connect(url, port); //連接ftp服務(wù)器 //如果采用默認(rèn)端口,可以使用ftp.connect(url)的方式直接連接ftp服務(wù)器 ftp.login(username, password); //登錄 reply = ftp.getreplycode(); if (!ftpreply.ispositivecompletion(reply)) { ftp.disconnect(); return success; } //創(chuàng)建路徑 try { ftp.makedirectory(path); } catch (exception e){ } ftp.enterlocalpassivemode(); ftp.changeworkingdirectory(path); boolean f= ftp.storefile(filename, input); logger.error(f); input.close(); ftp.logout(); success = true ; } catch (ioexception e) { e.printstacktrace(); } finally { if (ftp.isconnected()) { try { ftp.disconnect(); } catch (ioexception ioe) { } } } return success; } |
一些細(xì)節(jié)
fileinputstream.available()返回的實(shí)際可讀字節(jié)數(shù),也就是總大小。
ftpclient.storefile()方法時(shí),就停止在那里,什么反應(yīng)都沒(méi)有,出現(xiàn)假死狀態(tài)。
解決方法: 調(diào)用ftpclient.enterlocalpassivemode()
原 理: 因?yàn)閒tp server可能每次開(kāi)啟不同的端口來(lái)傳輸數(shù)據(jù),但是在linux上或者其他服務(wù)器上面,由于安全限制,可能某些端口沒(méi)有開(kāi)啟,所以就出現(xiàn)阻塞
ftp默認(rèn)端口為21 ssh為22 實(shí)際傳輸端口為20
查看指定端口,例21
netstat -na|grep 21(端口號(hào))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/emily_www/article/details/54926282