fpclient 實現上傳文件到指定服務器,供大家參考,具體內容如下
調用
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服務器上傳文件 * @param url ftp服務器hostname * @param port ftp服務器端口 * @param username ftp登錄賬號 * @param password ftp登錄密碼 * @param path ftp服務器保存目錄 * @param filename 上傳到ftp服務器上的文件名 * @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服務器 //如果采用默認端口,可以使用ftp.connect(url)的方式直接連接ftp服務器 ftp.login(username, password); //登錄 reply = ftp.getreplycode(); if (!ftpreply.ispositivecompletion(reply)) { ftp.disconnect(); return success; } //創建路徑 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; } |
一些細節
fileinputstream.available()返回的實際可讀字節數,也就是總大小。
ftpclient.storefile()方法時,就停止在那里,什么反應都沒有,出現假死狀態。
解決方法: 調用ftpclient.enterlocalpassivemode()
原 理: 因為ftp server可能每次開啟不同的端口來傳輸數據,但是在linux上或者其他服務器上面,由于安全限制,可能某些端口沒有開啟,所以就出現阻塞
ftp默認端口為21 ssh為22 實際傳輸端口為20
查看指定端口,例21
netstat -na|grep 21(端口號)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/emily_www/article/details/54926282