频道分类

如何在Delphi XE中通过FTP下载文件

作者:admin 来源: 日期:2020/11/11 8:50:22 人气: 标签:

 
uses
 ... IdFTP, IdFTPCommon ...
 
procedure TForm1.Button1Click(Sender: TObject);
begin
  IdFTP1.Host := 'test.rebex.net';
  IdFTP1.Port := 21;
  IdFTP1.ConnectTimeout := 5000;
  IdFTP1.Username := 'demo';
  IdFTP1.Password := 'password';
  IdFTP1.TransferType := IdFTPCommon.TIdFTPTransferType.ftBinary;
  IdFTP1.Passive := True;
 
  try
    IdFTP1.Connect;
    try
      IdFTP1.Get('/pub/example/pop3-browser.png', ExtractFilePath(ParamStr(0)) + 'pop3-browser.png', True, False);
    finally
      IdFTP1.Disconnect;
    end;
    ShowMessage('Downloaded!');
  except
    ShowMessage('Error while downloading!');
  end;
end;
如果FTP服务器仅允许匿名连接,请使用:

IdFTP1.Username:='匿名';
//IdFTP1.Password:='password';

使用TIdURI在Delphi XE中解析或拆分FTP URL
uses
 ... IdFTP, IdFTPCommon, IdURI ...
 
procedure TForm1.btnDownloadFileClick(Sender: TObject);
var
  URL: string;
  Uri: TIdURI;
begin
  URL := Trim(edURL.Text);
  Uri := TIdURI.Create(URL);
 
  try
    IdFTP1.Host := Uri.Host;
 
    if Uri.Port <> '' then
    IdFTP1.Port := StrToInt(Uri.Port) else
    IdFTP1.Port := 21;
 
    IdFTP1.ConnectTimeout := 5000;
 
    IdFTP1.Username := 'anonymous';
 
    if Uri.Username <> '' then
    begin
      IdFTP1.Username := Uri.Username;
      IdFTP1.Password := Uri.Password;
    end;
 
    IdFTP1.TransferType := IdFTPCommon.TIdFTPTransferType.ftBinary;
    IdFTP1.Passive := True;
 
    try
      IdFTP1.Connect;
      try
        IdFTP1.Get(Uri.Path + Uri.Document, ExtractFilePath(ParamStr(0)) + Uri.Document, True, False);
      finally
        IdFTP1.Disconnect;
      end;
      ShowMessage('Downloaded!');
    except
      ShowMessage('Error while downloading!');
    end;
  finally
    Uri.Free;
  end;
end;
适用于username:password和匿名FTP登录名:

ftp:// demo:password@test.rebex.net/pub/example/pop3-browser.png
ftp://speedtest.tele2.net/1MB.zip
有关TIdURI的更多详细信息,请参见:

http://www.e-iter.net/knowledge/indy9/007878.html