由于delphi本身自带了indy控件,因此用这些控件实现网络编程即快又容易。尽管如此,我还是极大地鼓励自己查看FTP底层是如何实现的,但就目前而言,indy控件还是一个非常不错的选择。
针对indy的强大,我还是决定将这段代码帖出来,主要是方便自己日后复习、查询。
Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdFTP;
type
TForm1 = class(TForm)
IdFTP1: TIdFTP;
Button1: TButton;
Memo1: TMemo;
Edit1: TEdit;
Button2: TButton;
Label1: TLabel;
Button3: TButton;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure IdFTP1Status(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: String);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses IdFTPList, IdFTPCommon;
{$R *.dfm}
{
本程序是一个ftp demo程序,我用windows信息服务在本机建立了一个ftp服务,
本机IP:192.168.10.99
用户名:cc
密码:1
}
procedure TForm1.Button1Click(Sender: TObject);
var
tr : Tstrings;
begin //连接
tr := TStringlist.Create;
IdFTP1.Host := '192.168.10.99'; //FTP服务器地址
IdFTP1.Username := 'cc'; //FTP服务器用户名
IdFTP1.Password := '1'; //FTP服务器密码
IdFTP1.Connect(); //连接到ftp
Edit1.Text := IdFTP1.RetrieveCurrentDir;//得到初始目录
IdFTP1.ChangeDir('client'); //进入到client子目录
//IdFTP1.ChangeDir('..'); //回到上一级目录
IdFTP1.List(tr); //得到client目录下所有文件列表
Memo1.Lines.Assign(tr);
tr.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
tt :TIdFTPListItems;
t : TIdFTPListItem;
i : integer;
tfname : String;
begin //下载
Label1.Caption := IdFTP1.DirectoryListing.Items[0].FileName;
IdFTP1.TransferType := ftBinary; //指定为二进制文件 或文本文件ftASCII
for i:=0 to IdFTP1.DirectoryListing.Count-1 do
begin
tt := IdFTP1.DirectoryListing; //得到当前目录下文件及目录列表
t := tt.Items[i]; //得到一个文件相关信息
Label1.Caption :=t.Text; //取出一个文件信息内容
tfname := t.FileName;
showmessage(t.OwnerName+' '+t.GroupName+' '+t.FileName+' '+t.LinkedItemName);
if IdFTP1.DirectoryListing.Items[i].ItemType = ditFile then //如果是文件
begin
IdFTP1.Get(tfname,'d:/FTPtest/'+tfname,True,True); //下载到本地,并为覆盖,且支持断点续传
end;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
fi : string;
begin //上传
if OpenDialog1.Execute then
begin
fi := OpenDialog1.FileName;
IdFTP1.Put('f:/测试文档样本.rar','测试文档样本.rar');//上传,
end;
end;
procedure TForm1.IdFTP1Status(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: String);
begin
{case AStatus of
hsResolving : showmessage('hsResolving');
hsConnecting: showmessage('hsConnecting');
hsConnected: showmessage('hsConnected');
hsDisconnecting: showmessage('hsDisconnecting');
hsDisconnected: showmessage('hsDisconnected');
hsStatusText: showmessage('hsStatusText');
ftpTransfer: showmessage('文件传送完毕。');
ftpReady: showmessage('准备传送文件....');
ftpAborted: showmessage('传送失败');
end; }
//showmessage(AStatusText);
end;
end.