当前位置:首页 » 文件管理 » 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 13:56:06 浏览:29
手文件夹恢复 发布:2025-05-17 13:53:32 浏览:992
linux怎么看进程 发布:2025-05-17 13:53:30 浏览:302
thinkphp字段缓存 发布:2025-05-17 13:52:01 浏览:574
山灵app安卓版如何设置 发布:2025-05-17 13:51:49 浏览:387
帆布压缩袋 发布:2025-05-17 13:26:27 浏览:457
c语言16进制表示方法 发布:2025-05-17 13:11:25 浏览:480
ftp单位 发布:2025-05-17 13:10:03 浏览:142
c语言编写n的阶乘 发布:2025-05-17 13:10:02 浏览:685
lockjava 发布:2025-05-17 13:02:08 浏览:311