當前位置:首頁 » 文件管理 » ftpclose函數

ftpclose函數

發布時間: 2023-03-20 04:47:29

A. 用python寫測試腳本,從本地傳文件至ftp遠程路徑

轉自:http://news.tuxi.com.cn/kf/article/jhtdj.htm

本文實例講述了python實現支持目錄FTP上傳下載文件的方法。分享給大家供大家參考。具體如下:

該程序支持ftp上傳下載文件和目錄、適用於windows和linux平台。

#!/usr/bin/envpython
#-*-coding:utf-8-*-
importftplib
importos
importsys
classFTPSync(object):
conn=ftplib.FTP()
def__init__(self,host,port=21):
self.conn.connect(host,port)
deflogin(self,username,password):
self.conn.login(username,password)
self.conn.set_pasv(False)
printself.conn.welcome
deftest(self,ftp_path):
printftp_path
printself._is_ftp_dir(ftp_path)
#printself.conn.nlst(ftp_path)
#self.conn.retrlines('LIST./a/b')
#ftp_parent_path=os.path.dirname(ftp_path)
#ftp_dir_name=os.path.basename(ftp_path)
#printftp_parent_path
#printftp_dir_name
def_is_ftp_file(self,ftp_path):
try:
ifftp_pathinself.conn.nlst(os.path.dirname(ftp_path)):
returnTrue
else:
returnFalse
exceptftplib.error_perm,e:
returnFalse
def_ftp_list(self,line):
list=line.split('')
ifself.ftp_dir_name==list[-1]andlist[0].startswith('d'):
self._is_dir=True
def_is_ftp_dir(self,ftp_path):
ftp_path=ftp_path.rstrip('/')
ftp_parent_path=os.path.dirname(ftp_path)
self.ftp_dir_name=os.path.basename(ftp_path)
self._is_dir=False
ifftp_path=='.'orftp_path=='./'orftp_path=='':
self._is_dir=True
else:
#thisuescallbackfunction,thatwillchange_is_dirvalue
try:
self.conn.retrlines('LIST%s'%ftp_parent_path,self._ftp_list)
exceptftplib.error_perm,e:
returnself._is_dir
returnself._is_dir
defget_file(self,ftp_path,local_path='.'):
ftp_path=ftp_path.rstrip('/')
ifself._is_ftp_file(ftp_path):
file_name=os.path.basename(ftp_path)
#如果本地路徑是目錄,下載文件到該目錄
ifos.path.isdir(local_path):
file_handler=open(os.path.join(local_path,file_name),'wb')
self.conn.retrbinary("RETR%s"%(ftp_path),file_handler.write)
file_handler.close()
#如果本地路徑不是目錄,但上層目錄存在,則按照本地路徑的文件名作為下載的文件名稱
elifos.path.isdir(os.path.dirname(local_path)):
file_handler=open(local_path,'wb')
self.conn.retrbinary("RETR%s"%(ftp_path),file_handler.write)
file_handler.close()
#如果本地路徑不是目錄,且上層目錄不存在,則退出
else:
print'EROOR:Thedir:%sisnotexist'%os.path.dirname(local_path)
else:
print'EROOR:Theftpfile:%sisnotexist'%ftp_path
defput_file(self,local_path,ftp_path='.'):
ftp_path=ftp_path.rstrip('/')
ifos.path.isfile(local_path):
file_handler=open(local_path,"r")
local_file_name=os.path.basename(local_path)
#如果遠程路徑是個目錄,則上傳文件到這個目錄,文件名不變
ifself._is_ftp_dir(ftp_path):
self.conn.storbinary('STOR%s'%os.path.join(ftp_path,local_file_name),file_handler)
#如果遠程路徑的上層是個目錄,則上傳文件,文件名按照給定命名
elifself._is_ftp_dir(os.path.dirname(ftp_path)):
print'STOR%s'%ftp_path
self.conn.storbinary('STOR%s'%ftp_path,file_handler)
#如果遠程路徑不是目錄,且上一層的目錄也不存在,則提示給定遠程路徑錯誤
else:
print'EROOR:Theftppath:%siserror'%ftp_path
file_handler.close()
else:
print'ERROR:Thefile:%sisnotexist'%local_path
defget_dir(self,ftp_path,local_path='.',begin=True):
ftp_path=ftp_path.rstrip('/')
#當ftp目錄存在時下載
ifself._is_ftp_dir(ftp_path):
#如果下載到本地當前目錄下,並創建目錄
#下載初始化:如果給定的本地路徑不存在需要創建,同時將ftp的目錄存放在給定的本地目錄下。
#ftp目錄下文件存放的路徑為local_path=local_path+os.path.basename(ftp_path)
#例如:將ftp文件夾a下載到本地的a/b目錄下,則ftp的a目錄下的文件將下載到本地的a/b/a目錄下
ifbegin:
ifnotos.path.isdir(local_path):
os.makedirs(local_path)
local_path=os.path.join(local_path,os.path.basename(ftp_path))
#如果本地目錄不存在,則創建目錄
ifnotos.path.isdir(local_path):
os.makedirs(local_path)
#進入ftp目錄,開始遞歸查詢
self.conn.cwd(ftp_path)
ftp_files=self.conn.nlst()
forfileinftp_files:
local_file=os.path.join(local_path,file)
#如果fileftp路徑是目錄則遞歸上傳目錄(不需要再進行初始化begin的標志修改為False)
#如果fileftp路徑是文件則直接上傳文件
ifself._is_ftp_dir(file):
self.get_dir(file,local_file,False)
else:
self.get_file(file,local_file)
#如果當前ftp目錄文件已經遍歷完畢返回上一層目錄
self.conn.cwd("..")
return
else:
print'ERROR:Thedir:%sisnotexist'%ftp_path
return

defput_dir(self,local_path,ftp_path='.',begin=True):
ftp_path=ftp_path.rstrip('/')
#當本地目錄存在時上傳
ifos.path.isdir(local_path):
#上傳初始化:如果給定的ftp路徑不存在需要創建,同時將本地的目錄存放在給定的ftp目錄下。
#本地目錄下文件存放的路徑為ftp_path=ftp_path+os.path.basename(local_path)
#例如:將本地文件夾a上傳到ftp的a/b目錄下,則本地a目錄下的文件將上傳的ftp的a/b/a目錄下
ifbegin:
ifnotself._is_ftp_dir(ftp_path):
self.conn.mkd(ftp_path)
ftp_path=os.path.join(ftp_path,os.path.basename(local_path))
#如果ftp路徑不是目錄,則創建目錄
ifnotself._is_ftp_dir(ftp_path):
self.conn.mkd(ftp_path)

#進入本地目錄,開始遞歸查詢
os.chdir(local_path)
local_files=os.listdir('.')
forfileinlocal_files:
#如果file本地路徑是目錄則遞歸上傳目錄(不需要再進行初始化begin的標志修改為False)
#如果file本地路徑是文件則直接上傳文件
ifos.path.isdir(file):
ftp_path=os.path.join(ftp_path,file)
self.put_dir(file,ftp_path,False)
else:
self.put_file(file,ftp_path)
#如果當前本地目錄文件已經遍歷完畢返回上一層目錄
os.chdir("..")
else:
print'ERROR:Thedir:%sisnotexist'%local_path
return
if__name__=='__main__':
ftp=FTPSync('192.168.1.110')
ftp.login('test','test')
#上傳文件,不重命名
#ftp.put_file('111.txt','a/b')
#上傳文件,重命名
#ftp.put_file('111.txt','a/112.txt')
#下載文件,不重命名
#ftp.get_file('/a/111.txt',r'D:\')
#下載文件,重命名
#ftp.get_file('/a/111.txt',r'D:112.txt')
#下載到已經存在的文件夾
#ftp.get_dir('a/b/c',r'D:\a')
#下載到不存在的文件夾
#ftp.get_dir('a/b/c',r'D:\aa')
#上傳到已經存在的文件夾
ftp.put_dir('b','a')
#上傳到不存在的文件夾
ftp.put_dir('b','aa/B/')

希望本文所述對大家的Python程序設計有所幫助。

以下轉自:http://blog.csdn.net/linda1000/article/details/8255771

Python中的ftplib模塊

Python中默認安裝的ftplib模塊定義了FTP類,其中函數有限,可用來實現簡單的ftp客戶端,用於上傳或下載文件

FTP的工作流程及基本操作可參考協議RFC959

ftp登陸連接

from ftplib import FTP #載入ftp模塊

ftp=FTP() #設置變數
ftp.set_debuglevel(2) #打開調試級別2,顯示詳細信息
ftp.connect("IP","port") #連接的ftp sever和埠
ftp.login("user","password")#連接的用戶名,密碼
print ftp.getwelcome() #列印出歡迎信息
ftp.cmd("xxx/xxx") #更改遠程目錄
bufsize=1024 #設置的緩沖區大小
filename="filename.txt" #需要下載的文件
file_handle=open(filename,"wb").write #以寫模式在本地打開文件
ftp.retrbinaly("RETR filename.txt",file_handle,bufsize) #接收伺服器上文件並寫入本地文件
ftp.set_debuglevel(0) #關閉調試模式
ftp.quit #退出ftp

ftp相關命令操作

ftp.cwd(pathname) #設置FTP當前操作的路徑
ftp.dir() #顯示目錄下文件信息
ftp.nlst() #獲取目錄下的文件
ftp.mkd(pathname) #新建遠程目錄
ftp.pwd() #返回當前所在位置
ftp.rmd(dirname) #刪除遠程目錄
ftp.delete(filename) #刪除遠程文件
ftp.rename(fromname, toname)#將fromname修改名稱為toname。
ftp.storbinaly("STOR filename.txt",file_handel,bufsize) #上傳目標文件
ftp.retrbinary("RETR filename.txt",file_handel,bufsize)#下載FTP文件

網上找到一個具體的例子:

#例:FTP編程
fromftplibimportFTP

ftp=FTP()
timeout=30
port=21
ftp.connect('192.168.1.188',port,timeout)#連接FTP伺服器
ftp.login('UserName','888888')#登錄
printftp.getwelcome()#獲得歡迎信息
ftp.cwd('file/test')#設置FTP路徑
list=ftp.nlst()#獲得目錄列表
fornameinlist:
print(name)#列印文件名字
path='d:/data/'+name#文件保存路徑
f=open(path,'wb')#打開要保存文件
filename='RETR'+name#保存FTP文件
ftp.retrbinary(filename,f.write)#保存FTP上的文件
ftp.delete(name)#刪除FTP文件
ftp.storbinary('STOR'+filename,open(path,'rb'))#上傳FTP文件
ftp.quit()#退出FTP伺服器

完整的模板:

#!/usr/bin/python
#-*-coding:utf-8-*-
importftplib
importos
importsocket

HOST='ftp.mozilla.org'
DIRN='pub/mozilla.org/webtools'
FILE='bugzilla-3.6.7.tar.gz'
defmain():
try:
f=ftplib.FTP(HOST)
except(socket.error,socket.gaierror):
print'ERROR:cannotreach"%s"'%HOST
return
print'***Connectedtohost"%s"'%HOST

try:
f.login()
exceptftplib.error_perm:
print'ERROR:cannotloginanonymously'
f.quit()
return
print'***Loggedinas"anonymously"'
try:
f.cwd(DIRN)
exceptftplib.error_perm:
print'ERRORLcannotCDto"%s"'%DIRN
f.quit()
return
print'***Changedto"%s"folder'%DIRN
try:
#傳一個回調函數給retrbinary()它在每接收一個二進制數據時都會被調用
f.retrbinary('RETR%s'%FILE,open(FILE,'wb').write)
exceptftplib.error_perm:
print'ERROR:cannotreadfile"%s"'%FILE
os.unlink(FILE)
else:
print'***Downloaded"%s"toCWD'%FILE
f.quit()
return

if__name__=='__main__':
main()

B. 怎麼用java實現FTP上傳

sun.net.ftp.FtpClient.,該類庫主要提供了用於建立FTP連接的類。利用這些類的方法,編程人員可以遠程登錄到FTP伺服器,列舉該伺服器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵蓋了幾乎所有FTP的功能,FtpClient的實例變數保存了有關建立"代理"的各種信息。下面給出了這些實例變數:
public static boolean useFtpProxy
這個變數用於表明FTP傳輸過程中是否使用了一個代理,因此,它實際上是一個標記,此標記若為TRUE,表明使用了一個代理主機。
public static String ftpProxyHost
此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機名。
public static int ftpProxyPort此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機的埠地址。
FtpClient有三種不同形式的構造函數,如下所示:
1、public FtpClient(String hostname,int port)
此構造函數利用給出的主機名和埠號建立一條FTP連接。
2、public FtpClient(String hostname)
此構造函數利用給出的主機名建立一條FTP連接,使用默認埠號。
3、FtpClient()
此構造函數將創建一FtpClient類,但不建立FTP連接。這時,FTP連接可以用openServer方法建立。
一旦建立了類FtpClient,就可以用這個類的方法來打開與FTP伺服器的連接。類ftpClient提供了如下兩個可用於打開與FTP伺服器之間的連接的方法。
public void openServer(String hostname)
這個方法用於建立一條與指定主機上的FTP伺服器的連接,使用默認埠號。
public void openServer(String host,int port)
這個方法用於建立一條與指定主機、指定埠上的FTP伺服器的連接。
打開連接之後,接下來的工作是注冊到FTP伺服器。這時需要利用下面的方法。
public void login(String username,String password)
此方法利用參數username和password登錄到FTP伺服器。使用過Intemet的用戶應該知道,匿名FTP伺服器的登錄用戶名為anonymous,密碼一般用自己的電子郵件地址。
下面是FtpClient類所提供的一些控制命令。
public void cd(String remoteDirectory):該命令用於把遠程系統上的目錄切換到參數remoteDirectory所指定的目錄。
public void cdUp():該命令用於把遠程系統上的目錄切換到上一級目錄。
public String pwd():該命令可顯示遠程系統上的目錄狀態。
public void binary():該命令可把傳輸格式設置為二進制格式。
public void ascii():該命令可把傳輸協議設置為ASCII碼格式。
public void rename(String string,String string1):該命令可對遠程系統上的目錄或者文件進行重命名操作。
除了上述方法外,類FtpClient還提供了可用於傳遞並檢索目錄清單和文件的若干方法。這些方法返回的是可供讀或寫的輸入、輸出流。下面是其中一些主要的方法。
public TelnetInputStream list()
返回與遠程機器上當前目錄相對應的輸入流。
public TelnetInputStream get(String filename)
獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。
public TelnetOutputStream put(String filename)
以寫方式打開一輸出流,通過這一輸出流把文件filename傳送到遠程計算機

package myUtil;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* ftp上傳,下載

*
* @author why 2009-07-30
*
*/
public class FtpUtil {
private String ip = "";
private String username = "";
private String password = "";
private int port = -1;
private String path = "";
FtpClient ftpClient = null;
OutputStream os = null;
FileInputStream is = null;
public FtpUtil(String serverIP, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
}
public FtpUtil(String serverIP, int port, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
/**
* 連接ftp伺服器
*
* @throws IOException
*/
public boolean connectServer() {
ftpClient = new FtpClient();
try {
if (this.port != -1) {
ftpClient.openServer(this.ip, this.port);
} else {
ftpClient.openServer(this.ip);
}
ftpClient.login(this.username, this.password);
if (this.path.length() != 0) {
ftpClient.cd(this.path);// path是ftp服務下主目錄的子目錄
}
ftpClient.binary();// 用2進制上傳、下載
System.out.println("已登錄到\"" + ftpClient.pwd() + "\"目錄");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 斷開與ftp伺服器連接
*
* @throws IOException
*/
public boolean closeServer() {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
System.out.println("已從伺服器斷開");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 檢查文件夾在當前目錄下是否存在
*
* @param dir
*@return
*/
private boolean isDirExist(String dir) {
String pwd = "";
try {
pwd = ftpClient.pwd();
ftpClient.cd(dir);
ftpClient.cd(pwd);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 在當前目錄下創建文件夾
*
* @param dir
* @return
* @throws Exception
*/
private boolean createDir(String dir) {
try {
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/"); // sign
s.countTokens();
String pathName = ftpClient.pwd();
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpClient.sendServer("MKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
return false;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
/**
* ftp上傳 如果伺服器段已存在名為filename的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
*
* @param filename
* 要上傳的文件(或文件夾)名
* @return
* @throws Exception
*/
public boolean upload(String filename) {
String newname = "";
if (filename.indexOf("/") > -1) {
newname = filename.substring(filename.lastIndexOf("/") + 1);
} else {
newname = filename;
}
return upload(filename, newname);
}
/**
* ftp上傳 如果伺服器段已存在名為newName的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
*
* @param fileName
* 要上傳的文件(或文件夾)名
* @param newName
* 伺服器段要生成的文件(或文件夾)名
* @return
*/
public boolean upload(String fileName, String newName) {
try {
String savefilename = new String(fileName.getBytes("GBK"),
"GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
upload(file_in.getPath(), newName, ftpClient.pwd());
} else {
uploadFile(file_in.getPath(), newName);
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 真正用於上傳的方法
*
* @param fileName
* @param newName
* @param path
* @throws Exception
*/
private void upload(String fileName, String newName, String path)
throws Exception {
String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
if (!isDirExist(newName)) {
createDir(newName);
}
ftpClient.cd(newName);
File sourceFile[] = file_in.listFiles();
for (int i = 0; i < sourceFile.length; i++) {
if (!sourceFile[i].exists()) {
continue;
}
if (sourceFile[i].isDirectory()) {
this.upload(sourceFile[i].getPath(), sourceFile[i]
.getName(), path + "/" + newName);
} else {
this.uploadFile(sourceFile[i].getPath(), sourceFile[i]
.getName());
}
}
} else {
uploadFile(file_in.getPath(), newName);
}
ftpClient.cd(path);
}
/**
* upload 上傳文件
*
* @param filename
* 要上傳的文件名
* @param newname
* 上傳後的新文件名
* @return -1 文件不存在 >=0 成功上傳,返迴文件的大小
* @throws Exception
*/
public long uploadFile(String filename, String newname) throws Exception {
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
java.io.File file_in = new java.io.File(filename);
if (!file_in.exists())
return -1;
os = ftpClient.put(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* 從ftp下載文件到本地
*
* @param filename
* 伺服器上的文件名
* @param newfilename
* 本地生成的文件名
* @return
* @throws Exception
*/
public long downloadFile(String filename, String newfilename) {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
try {
is = ftpClient.get(filename);
java.io.File outfile = new java.io.File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 取得相對於當前連接目錄的某個目錄下所有文件列表
*
* @param path
* @return
*/
public List getFileList(String path) {
List list = new ArrayList();
DataInputStream dis;
try {
dis = new DataInputStream(ftpClient.nameList(this.path + path));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
FtpUtil ftp = new FtpUtil("192.168.11.11", "111", "1111");
ftp.connectServer();
boolean result = ftp.upload("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");
System.out.println(result ? "上傳成功!" : "上傳失敗!");
ftp.closeServer();
/**
* FTP遠程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASV STOR
* REST CWD STAT RMD XCUP OPTS ACCT TYPE APPE RNFR XCWD HELP XRMD STOU
* AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ QUIT MODE SYST ABOR
* NLST MKD XPWD MDTM PROT
* 在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\n
* ftpclient.sendServer("XMKD /test/bb\r\n"); //執行伺服器上的FTP命令
* ftpclient.readServerResponse一定要在sendServer後調用
* nameList("/test")獲取指目錄下的文件列表 XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯 XRMD刪除目錄
* DELE刪除文件
*/
}
}

C. JAVA 如何實現FTP遠程路徑

package nc.ui.doc.doc_007;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import nc.itf.doc.DocDelegator;
import nc.vo.doc.doc_007.DirVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTP;

public class FtpTool {

private FTPClient ftp;

private String romateDir = "";

private String userName = "";

private String password = "";

private String host = "";

private String port = "21";

public FtpTool(String url) throws IOException {
//String url="ftp://user:password@ip:port/ftptest/psd";
int len = url.indexOf("//");
String strTemp = url.substring(len + 2);
len = strTemp.indexOf(":");
userName = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);

len = strTemp.indexOf("@");
password = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
host = "";
len = strTemp.indexOf(":");
if (len < 0)//沒有設置埠
{
port = "21";
len = strTemp.indexOf("/");
if (len > -1) {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
strTemp = "";
}
} else {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("/");
if (len > -1) {
port = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
port = "21";
strTemp = "";
}
}
romateDir = strTemp;
ftp = new FTPClient();
ftp.connect(host, FormatStringToInt(port));

}

public FtpTool(String host, int port) throws IOException {
ftp = new FTPClient();
ftp.connect(host, port);
}

public String login(String username, String password) throws IOException {
this.ftp.login(username, password);
return this.ftp.getReplyString();
}

public String login() throws IOException {
this.ftp.login(userName, password);
System.out.println("ftp用戶: " + userName);
System.out.println("ftp密碼: " + password);
if (!romateDir.equals(""))
System.out.println("cd " + romateDir);
ftp.changeWorkingDirectory(romateDir);
return this.ftp.getReplyString();
}

public boolean upload(String pathname, String filename) throws IOException, BusinessException {

int reply;
int j;
String m_sfilename = null;
filename = CheckNullString(filename);
if (filename.equals(""))
return false;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("FTP server refused connection.");
System.exit(1);
}
FileInputStream is = null;
try {
File file_in;
if (pathname.endsWith(File.separator)) {
file_in = new File(pathname + filename);
} else {
file_in = new File(pathname + File.separator + filename);
}
if (file_in.length() == 0) {
System.out.println("上傳文件為空!");
return false;
}
//產生隨機數最大到99
j = (int)(Math.random()*100);
m_sfilename = String.valueOf(j) + ".pdf"; // 生成的文件名
is = new FileInputStream(file_in);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.storeFile(m_sfilename, is);
ftp.logout();

} finally {
if (is != null) {
is.close();
}
}
System.out.println("上傳文件成功!");
return true;
}

public boolean delete(String filename) throws IOException {

FileInputStream is = null;
boolean retValue = false;
try {
retValue = ftp.deleteFile(filename);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
return retValue;

}

public void close() {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static int FormatStringToInt(String p_String) {
int intRe = 0;
if (p_String != null) {
if (!p_String.trim().equals("")) {
try {
intRe = Integer.parseInt(p_String);
} catch (Exception ex) {

}
}
}
return intRe;
}

public static String CheckNullString(String p_String) {
if (p_String == null)
return "";
else
return p_String;
}

public boolean downfile(String pathname, String filename) {

String outputFileName = null;
boolean retValue = false;
try {
FTPFile files[] = ftp.listFiles();
int reply = ftp.getReplyCode();

////////////////////////////////////////////////
if (!FTPReply.isPositiveCompletion(reply)) {
try {
throw new Exception("Unable to get list of files to dowload.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/////////////////////////////////////////////////////
if (files.length == 0) {
System.out.println("No files are available for download.");
}else {
for (int i=0; i <files.length; i++) {
System.out.println("Downloading file "+files[i].getName()+"Size:"+files[i].getSize());
outputFileName = pathname + filename + ".pdf";
//return outputFileName;
File f = new File(outputFileName);

//////////////////////////////////////////////////////
retValue = ftp.retrieveFile(outputFileName, new FileOutputStream(f));

if (!retValue) {
try {
throw new Exception ("Downloading of remote file"+files[i].getName()+" failed. ftp.retrieveFile() returned false.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

/////////////////////////////////////////////////////////////
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retValue;
}

}

D. 關於如何實現FTP上傳或者下載帶進度和速率的實現方法

在這里需要說明的是,該方式是通過其他代碼進行改進的。 首先我們需要定義一個委託,用來實現傳輸過程中傳遞文件的總數,已完成的位元組數和速度,方便客戶端界面上調用。 public delegate void TransferProcess(long total,long finished,double speed); 調用代碼就不舉例了 接下來我們建立一個FTPClient類,該類基於socket和FTP協議實現了連接FTP服務,建立目錄,上傳文件,下載文件等主要方法。結構如下: 需要注意的是,我們需要定一個事件event TransferProcess OnTransferProcess;該事件在實例化FTPClient之後需要調用,這個事件對實現進度條和速率是非常重要的。為了實現速率我們還需要定義個公開的成員startTime(開始時間)。我們現在主要是看一下如何上傳的。 /// /// 上傳一個文件 /// /// 本地文件名 public void Put(string strFileName) { //連接伺服器 if (!bConnected) { Connect(); } UpdateStatus = true; //建立socket連接 Socket socketData = CreateDataSocket(); //向FTP伺服器發生存儲命令 SendCommand("STOR " + Path.GetFileName(strFileName)); //如何伺服器返回的信息不是我們所需要的,就拋出異常 if (!(iReplyCode == 125 || iReplyCode == 150)) { throw new IOException(strReply.Substring(4)); } //建立本地文件的數據流 FileStream input = new FileStream(strFileName, FileMode.Open); int iBytes = 0; long total = input.Length;//該成員主要記錄文件的總位元組數,注意這里使用長整型,是為了突破只能傳輸2G左右的文件的限制 long finished = 0;//該成員主要記錄已經傳輸完成的位元組數,注意這里使用長整型,是為了突破只能傳輸2G左右的文件的限制 double speed = 0;//記錄傳輸的速率 while ((iBytes = input.Read(buffer, 0, buffer.Length)) > 0)//循環從本地數據流中讀取數據到緩沖區 { //Console.WriteLine(startTime.ToString()); socketData.Send(buffer, iBytes, 0);//將緩沖區的數據發送到FTP伺服器 DateTime endTime = DateTime.Now;//每次發送數據的結束時間 TimeSpan ts = endTime - startTime;//計算每次發送數據的時間間隔 finished += iBytes;//計算完成的位元組數. Console.WriteLine(ts.Milliseconds); //計算速率,注意finished是位元組,所以需要換算沖K位元組 if (ts.Milliseconds > 0) { speed = (double)(finished / ts.TotalMilliseconds); speed = Math.Round(speed * 1000 / 1024, 2); } //這里是必不可少的,否則你無法實現進度條 //如果傳輸進度事件被實例化,而且從本地數據流中讀取數據不是空的並完成的位元組數也不為空的話,則實現委託. if (OnTransferProcess != null&&iBytes>0&&finished>0) { OnTransferProcess(total, finished,speed); } } UpdateStatus = false; finished = 0; input.Close();//當傳輸完成之後需要關閉數據流,以便下次訪問. if (socketData.Connected) { socketData.Close();//關閉當前的socket } if (!(iReplyCode == 226 || iReplyCode == 250)) { ReadReply(); if (!(iReplyCode == 226 || iReplyCode == 250)) { UpdateStatus = false; throw new IOException(strReply.Substring(4)); } } } 上面代碼中注釋寫得比較詳細,這里就不再一一講解了,關於下載中實現進度條和速率的問題可以參考以上代碼進行修改. 完整的代碼如下: using System; using System.net; using System.IO; using System.Text; using System.net.Sockets; namespace MMSEncoder { public delegate void TransferProcess(long total,long finished,double speed); /// /// FTP Client /// public class FTPClient { public event TransferProcess OnTransferProcess; public bool UpdateStatus = true; public DateTime startTime; private bool IsAbortConnect = false; #region 構造函數 /// /// 預設構造函數 /// public FTPClient() { strRemoteHost = ""; strRemotePath = ""; strRemoteUser = ""; strRemotePass = ""; strRemotePort = 21; bConnected = false; } /// /// 構造函數 /// /// FTP伺服器IP地址 /// 當前伺服器目錄 /// 登錄用戶賬號 /// 登錄用戶密碼 /// FTP伺服器埠 public FTPClient(string remoteHost, string remotePath, string remoteUser, string remotePass, int remotePort) { strRemoteHost = remoteHost; strRemotePath = remotePath; strRemoteUser = remoteUser; strRemotePass = remotePass; strRemotePort = remotePort; Connect(); } #endregion #region 登陸欄位、屬性 /// /// FTP伺服器IP地址 /// private string strRemoteHost; public string RemoteHost { get { return strRemoteHost; } set { strRemoteHost = value; } } /// /// FTP伺服器埠 /// private int strRemotePort; public int RemotePort { get { return strRemotePort; } set { strRemotePort = value; } } /// /// 當前伺服器目錄 /// private string strRemotePath; public string RemotePath { get { return strRemotePath; } set { strRemotePath = value; } } /// /// 登錄用戶賬號 /// private string strRemoteUser; public string RemoteUser { set { strRemoteUser = value; } } /// /// 用戶登錄密碼 /// private string strRemotePass; public string RemotePass { set { strRemotePass = value; } } /// /// 是否登錄 /// private Boolean bConnected; public bool Connected { get { return bConnected; } } #endregion #region 鏈接 /// /// 建立連接 /// public void Connect() { //if (IsAbortConnect) throw new IOException("用戶強制終止了FTP"); socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort); // 鏈接 try { socketControl.Connect(ep); } catch (Exception) { throw new IOException("無法連接到遠程伺服器!"); } // 獲取應答碼 ReadReply(); if (iReplyCode != 220) { DisConnect(); throw new IOException(strReply.Substring(4)); } // 登陸 SendCommand("USER " + strRemoteUser); if (!(iReplyCode == 331 || iReplyCode == 230)) { CloseSocketConnect();//關閉連接 throw new IOException(strReply.Substring(4)); } if (iReplyCode != 230) { SendCommand("PASS " + strRemotePass); if (!(iReplyCode == 230 || iReplyCode == 202)) { CloseSocketConnect();//關閉連接 throw new IOException(strReply.Substring(4)); } } bConnected = true; // 切換到初始目錄 if (!string.IsNullOrEmpty(strRemotePath)) { ChDir(strRemotePath); } } /// /// 關閉連接 /// public void DisConnect() { if (socketControl != null) { SendCommand("QUIT"); } CloseSocketConnect(); } public void AbortConnect() { if (socketControl != null) { SendCommand("ABOR"); } IsAbortConnect = true; //CloseSocketConnect(); } #endregion #region 傳輸模式 /// /// 傳輸模式:二進制類型、ASCII類型 /// public enum TransferType { Binary, ASCII }; /// /// 設置傳輸模式 /// /// 傳輸模式 public void SetTransferType(TransferType ttType) { if (ttType == TransferType.Binary) { SendCommand("TYPE I");//binary類型傳輸 } else { SendCommand("TYPE A");//ASCII類型傳輸 } if (iReplyCode != 200) { throw new IOException(strReply.Substring(4)); } else { trType = ttType; } } /// /// 獲得傳輸模式 /// /// 傳輸模式 public TransferType GetTransferType() { return trType; } #endregion #region 文件操作 /// /// 獲得文件列表 /// /// 文件名的匹配字元串 /// public string[] Dir(string strMask) { // 建立鏈接 if (!bConnected) { Connect(); } //建立進行數據連接的socket Socket socketData = CreateDataSocket(); //傳送命令 SendCommand("NLST " + strMask); //分析應答代碼 if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226)) { throw new IOException(strReply.Substring(4)); } //獲得結果 strMsg = ""; while (true) { int iBytes = socketData.Receive(buffer, buffer.Length, 0); strMsg += GB2312.GetString(buffer, 0, iBytes); if (iBytes < buffer.Length) { break; } } char[] seperator = { '
' }; string[] strsFileList = strMsg.Split(seperator); socketData.Close();//數據socket關閉時也會有返回碼 if (iReplyCode != 226) { ReadReply(); if (iReplyCode != 226) { throw new IOException(strReply.Substring(4)); } } return strsFileList; } /// /// 獲取文件大小 /// /// 文件名 /// 文件大小 public long GetFileSize(string strFileName) { if (!bConnected) { Connect(); } SendCommand("SIZE " + Path.GetFileName(strFileName)); long lSize = 0; if (iReplyCode == 213) { lSize = Int64.Parse(strReply.Substring(4)); } else { throw new IOException(strReply.Substring(4)); } return lSize; } /// /// 刪除 /// /// 待刪除文件名 public void Delete(string strFileName) { if (!bConnected) { Connect(); } SendCommand("DELE " + strFileName); if (iReplyCode != 250) { throw new IOException(strReply.Substring(4)); } } /// /// 重命名(如果新文件名與已有文件重名,將覆蓋已有文件) /// /// 舊文件名 /// 新文件名 public void Rename(string strOldFileName, string strNewFileName) { if (!bConnected) { Connect(); } SendCommand("RNFR " + strOldFileName); if (iReplyCode != 350) { throw new IOException(strReply.Substring(4)); } // 如果新文件名與原有文件重名,將覆蓋原有文件 SendCommand("RNTO " + strNewFileName); if (iReplyCode != 250) { throw new IOException(strReply.Substring(4)); } } #endregion #region 上傳和下載 /// /// 下載一批文件 /// /// 文件名的匹配字元串 /// 本地目錄(不得以\結束) public void Get(string strFileNameMask, string strFolder) { if (!bConnected) { Connect(); } string[] strFiles = Dir(strFileNameMask); foreach (string strFile in strFiles) { if (!strFile.Equals(""))//一般來說strFiles的最後一個元素可能是空字元串 { if (strFile.LastIndexOf(".") > -1) { Get(strFile.Replace("\r", ""), strFolder, strFile.Replace("\r", "")); } } } } /// /// 下載一個文件 /// /// 要下載的文件名 /// 本地目錄(不得以\結束) /// 保存在本地時的文件名 public void Get(string strRemoteFileName, string strFolder, string strLocalFileName) { if (!bConnected) { Connect(); } SetTransferType(TransferType.Binary); if (strLocalFileName.Equals("")) { strLocalFileName = strRemoteFileName; } if (!File.Exists(strLocalFileName)) { Stream st = File.Create(strLocalFileName); st.Close(); } FileStream output = new FileStream(strFolder + "\\" + strLocalFileName, FileMode.Create); Socket socketData = CreateDataSocket(); SendCommand("RETR " + strRemoteFileName); if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226 || iReplyCode == 250)) { throw new IOException(strReply.Substring(4)); } while (true) { int iBytes = socketData.Receive(buffer, buffer.Length, 0); output.Write(buffer, 0, iBytes); if (iBytes <= 0) { break; } } output.Close(); if (socketData.Connected) { socketData.Close(); } if (!(iReplyCode == 226 || iReplyCode == 250)) { ReadReply(); if (!(iReplyCode == 226 || iReplyCode == 250)) { throw new IOException(strReply.Substring(4)); } } } /// /// 上傳一批文件 /// /// 本地目錄(不得以\結束) /// 文件名匹配字元(可以包含*和?) public void Put(string strFolder, string strFileNameMask) { string[] strFiles = Directory.GetFiles(strFolder, strFileNameMask); foreach (string strFile in strFiles) { //strFile是完整的文件名(包含路徑) Put(strFile); } } /// /// 上傳一個文件 /// /// 本地文件名 public void Put(string strFileName) { if (!bConnected) { Connect(); } UpdateStatus = true; Socket socketData = CreateDataSocket(); SendCommand("STOR " + Path.GetFileName(strFileName)); if (!(iReplyCode == 125 || iReplyCode == 150)) { throw new IOException(strReply.Substring(4)); } FileStream input = new FileStream(strFileName, FileMode.Open); int iBytes = 0; long total = input.Length; long finished = 0; //DateTime startTime = DateTime.Now; double speed = 0; while ((iBytes = input.Read(buffer, 0, buffer.Length)) > 0) { Console.WriteLine(startTime.ToString()); socketData.Send(buffer, iBytes, 0); DateTime endTime = DateTime.Now; TimeSpan ts = endTime - startTime; finished += iBytes; Console.WriteLine(ts.Milliseconds); if (ts.Milliseconds > 0) { speed = (double)(finished / ts.TotalMilliseconds); speed = Math.Round(speed * 1000 / 1024, 2); } if (OnTransferProcess != null&&iBytes>0&&finished>0) { OnTransferProcess(total, finished,speed); } } UpdateStatus = false; finished = 0; input.Close(); if (socketData.Connected) { socketData.Close(); } if (!(iReplyCode == 226 || iReplyCode == 250)) { ReadReply(); if (!(iReplyCode == 226 || iReplyCode == 250)) { UpdateStatus = false; throw new IOException(strReply.Substring(4)); } } } #endregion #region 目錄操作 /// /// 創建目錄 /// /// 目錄名 public void MkDir(string strDirName) { if (!bConnected) { Connect(); } SendCommand("MKD " + strDirName); if (iReplyCode != 257) { throw new IOException(strReply.Substring(4)); } } /// /// 刪除目錄 /// /// 目錄名 public void RmDir(string strDirName) { if (!bConnected) { Connect(); } SendCommand("RMD " + strDirName); if (iReplyCode != 250) { throw new IOException(strReply.Substring(4)); } } /// /// 改變目錄 /// /// 新的工作目錄名 public void ChDir(string strDirName) { if (strDirName.Equals(".") || strDirName.Equals("")) { return; } if (!bConnected) { Connect(); } SendCommand("CWD " + strDirName); if (iReplyCode != 250) { throw new IOException(strReply.Substring(4)); } this.strRemotePath = strDirName; } #endregion #region 內部變數 /// /// 伺服器返回的應答信息(包含應答碼) /// private string strMsg; /// /// 伺服器返回的應答信息(包含應答碼) /// private string strReply; /// /// 伺服器返回的應答碼 /// private int iReplyCode; /// /// 進行控制連接的socket /// private Socket socketControl; /// /// 傳輸模式 /// private TransferType trType; /// /// 接收和發送數據的緩沖區 /// private static int BLOCK_SIZE = Int16.MaxValue; Byte[] buffer = new Byte[BLOCK_SIZE]; /// /// 編碼方式(為防止出現中文亂碼採用 GB2312編碼方式) /// Encoding GB2312 = Encoding.Default ;//Encoding.GetEncoding("gb2312"); #endregion #region 內部函數 /// /// 將一行應答字元串記錄在strReply和strMsg /// 應答碼記錄在iReplyCode /// private void ReadReply() { strMsg = ""; strReply = ReadLine(); iReplyCode = Int32.Parse(strReply.Substring(0, 3)); } /// /// 建立進行數據連接的socket /// /// 數據連接socket private Socket CreateDataSocket() { SendCommand("PASV"); if (iReplyCode != 227) { throw new IOException(strReply.Substring(4)); } int index1 = strReply.IndexOf('('); int index2 = strReply.IndexOf(')'); string ipData = strReply.Substring(index1 + 1, index2 - index1 - 1); int[] parts = new int[6]; int len = ipData.Length; int partCount = 0; string buf = ""; for (int i = 0; i < len && partCount <= 6; i++) { char ch = Char.Parse(ipData.Substring(i, 1)); if (Char.IsDigit(ch)) buf += ch; else if (ch != ',') { throw new IOException("Malformed PASV strReply: " + strReply); } if (ch == ',' || i + 1 == len) { try { parts[partCount++] = Int32.Parse(buf); buf = ""; } catch (Exception) { throw new IOException("Malformed PASV strReply: " + strReply); } } } string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]; int port = (parts[4] << 8) + parts[5]; Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress), port); try { s.Connect(ep); } catch (Exception) { throw new IOException("無法連接伺服器"); } return s; } /// /// 關閉socket連接(用於登錄以前) /// private void CloseSocketConnect() { if (socketControl != null) { socketControl.Close(); socketControl = null; } bConnected = false; } /// /// 讀取Socket返回的所有字元串 /// /// 包含應答碼的字元串列 private string ReadLine() { while (true) { int iBytes = socketControl.Receive(buffer, buffer.Length, 0); strMsg += GB2312.GetString(buffer, 0, iBytes); if (iBytes < buffer.Length) { break; } } char[] seperator = { '
' }; string[] mess = strMsg.Split(seperator); if (strMsg.Length > 2) { strMsg = mess[mess.Length - 2]; //seperator[0]是10,換行符是由13和0組成的,分隔後10後面雖沒有字元串, //但也會分配為空字元串給後面(也是最後一個)字元串數組, //所以最後一個mess是沒用的空字元串 //但為什麼不直接取mess[0],因為只有最後一行字元串應答碼與信息之間有空格 } else { strMsg = mess[0]; } if (!strMsg.Substring(3, 1).Equals(" "))//返回字元串正確的是以應答碼(如220開頭,後面接一空格,再接問候字元串) { return ReadLine(); } return strMsg; } /// /// 發送命令並獲取應答碼和最後一行應答字元串 /// /// 命令 private void SendCommand(String strCommand) { Byte[] cmdBytes = GB2312.GetBytes((strCommand + "\r
").ToCharArray()); socketControl.Send(cmdBytes, cmdBytes.Length, 0); ReadReply(); } #endregion } }

E. 用php 中ftp函數抓取別人伺服器上的文件內容怎麼做啊

ftp_get -- 從 FTP 伺服器上下載一個文件
說明
bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_get() 函數用來下載 FTP 伺服器上由 remote_file 參數指定的文件,並保存到由參數 local_file 指定的本地文件。傳送碼槐模式參數 mode 只能為 (文本模式) FTP_ASCII 或 (二進制模式) FTP_BINARY 中的其中一個。

注: 參數 resumepos 僅在適用於 PHP 4.3.0 以上版本.

如果成功則返回 TRUE,失敗則返回灶知 FALSE。
ftp_get() 例子

<?php
// define some variables
$local_file = 'local.zip';
$server_file = 'server.zip';
// connect to the FTP server
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to download
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
// close the connection
ftp_close($conn_id);
?>
不知道你要的是遲辯友不是這個函數。

F. <php> file_get_contents() 可以通過ftp獲取內容嗎 我想獲取通過ftp上的文件。

通常,在 php 里獲取 ftp 伺服器上的文件,使用 ftp_get 及相關的 ftp 函數,以下是示例:


<?php
//definesomevariables
$local_file='local.zip';
$server_file='server.zip';
//connecttotheFTPserver
$conn_id=ftp_connect($ftp_server);
$login_result=ftp_login($conn_id,$ftp_user_name,$ftp_user_pass);
//trytodownload
if(ftp_get($conn_id,$local_file,$server_file,FTP_BINARY)){
echo洞族"Successfullywrittento$local_file";
}else{
岩顫搜echo"Therewasa粗歷problem";
}
//closetheconnection
ftp_close($conn_id);
?>

G. 用php如何把一些文件和圖片上傳到另一指定的伺服器

一個實例:

首先,在自己台式機和筆記本上都開通了ftp,這個不會的同學可以網上查serv-u,相關教程肯定不少的。

然後在台式機本地做了個測試:

$ftp_server = "192.168.1.100";
$ftp_user_name = "laohu";
$ftp_user_pass = "123456";
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$file = 'test.txt';
$remote_file = '/test/a.txt';
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
echo "文件移動成功\n";
} else {
echo "移動失敗\n";
}
ftp_close($conn_id);

運行後:文件移動成功。

要的就是這個效果了,之後用台式機做程序伺服器,上傳附件時全用ftp方法上傳至筆記本上,筆記本ip是105,相應代碼如下:

if (is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
$ftp_server = "192.168.1.105";
$ftp_user_name = "lesley";
$ftp_user_pass = "123456";
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$file = $_FILES['uploadfile']['tmp_name'];
$remote_file = '/test/'.$_FILES['uploadfile']['name'];
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
echo "文件:".$_FILES['uploadfile']['name']."上傳成功\n";
} else {
echo "上傳失敗\n";
}
ftp_close($conn_id);
}

對應的前台頁面代碼:

<form action="uploadfile.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadfile" id="uploadfile" />
<input type="submit" name="submit" value="submit" />
</form>

運行後確實成功。

需要注意:
在用ftp_put方法時,第四個參數傳送模式,需要用FTP_BINARY(二進制模式),用FTP_ASCII(文本模式)時,圖片能上傳但無法顯示,其他文件重命名、中文亂碼解決、上傳許可權控制等,就不在此提及了。

H. 如何禁止FTP,如何封堵FTP,FTP通訊協議和埠范圍

添加防火牆入站規則,
windows上禁止20、21兩個埠就可以了。
linux上,還有22埠是給ssh工具用的,如果也想阻止,就一起禁止掉。

I. 怎麼用cftpconnection類編寫向ftp server上傳文件

為了與FTP Internet伺服器通訊,必須先創建一個CInternetSession實例,然後創建CFtpConnection對象。創建CFtpConnection對象不採用直接方式,而是調用CInternetSession::GetFtpConnertion來創建並返回一個指向它的指針。

CFtpConnection類的成員

構造函數 CFtpConnection 構造一個CFtpConnection對象

操作 SetCurrentDirectory 設置當前FTP目錄

GetCurrentDirectory 獲取此次連接的當前目錄

GetCurrentDirectoryAsURL 獲取作為URL的此次連接的當前目錄

RemoveDirectory 從伺服器移去指定目錄

CreateDirectory 在伺服器上構造一個目錄

Rename 將伺服器上的文件改名

Remove 從伺服器上移去一個文件

PutFile 將一個文件放到伺服器上

GetFile 從連接的伺服器上獲取一個文件

OpenFile 在連接的伺服器上打開一個文件

Close 關閉與伺服器的連接

實例一:上傳文件
CString strAppName = AfxGetAppName();
CInternetSession* pSession = new CInternetSession(strAppName);
CFtpConnection* pConn = pSession->GetFtpConnection("
10.46.1.232","Anonymous","",21);
pConn->SetCurrentDirectory("test");
CString strLocfile,strRemotefile;
strLocfile="C:\\cmd.txt";
strRemotefile="cmd.txt";
pConn->PutFile(strLocfile,strRemotefile,FTP_TRANSFER_TYPE_ASCII);
pConn->Close();
return 0;
實例二:Ftp的打開文件操作函數:OpenFile

J. C語言如何用FtpPutFile()函數上傳文件到Ftp伺服器!下載用FtpGetFile()可以!

  1. 先後使用InternetOpen和InternetConnect打開連接。
  2. 使用CreateFile函數打開本地文件。
  3. 使用FtpOpenFile函數打開遠程文件。
  4. 分別使用InternetReadFile和ReadFile函數讀取 FTP 或本地文件。
  5. 分別使用InternetWriteFile和WriteFile函數寫入 FTP 或本地文件。
  6. 使用CloseHandle函數關閉本地文件句柄。
  7. 使用InternetCloseHandle函數關閉 FTP 文件句柄。

熱點內容
我的世界龍蛋伺服器 發布:2025-05-17 06:20:06 瀏覽:912
安卓系統軟體怎麼不更新 發布:2025-05-17 06:19:15 瀏覽:817
安卓夏日傳說存檔放哪個文件 發布:2025-05-17 06:12:44 瀏覽:606
如何通過伺服器id找到主人 發布:2025-05-17 06:12:11 瀏覽:37
ug編程吧 發布:2025-05-17 06:07:45 瀏覽:72
sql臨時表和表變數 發布:2025-05-17 06:02:38 瀏覽:724
蘋果如何用安卓無線耳機 發布:2025-05-17 06:01:53 瀏覽:822
sqlserver表關系 發布:2025-05-17 06:01:02 瀏覽:997
2017途觀配置什麼音響 發布:2025-05-17 05:53:50 瀏覽:844
64位安裝sql2000 發布:2025-05-17 05:33:17 瀏覽:846