Parse or Split FTP URL in Delphi XE using TIdURI

Posted on November 6, 2020 at 3:37 pm

Given an FTP URL, you can parse it using TidURI:

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;

Works with both username:password and anonymous FTP logins:

ftp://demo:password@test.rebex.net/pub/example/pop3-browser.png
ftp://speedtest.tele2.net/1MB.zip

More details on TIdURI here:

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

Receive updates via email

Other Posts

Updated Posts