Search code examples
delphilazarus

Download File from FTP-Server in Lazarus


I Need to download files from a FTP-Server with Lazarus. I have already a function for connecting to the Server but no idea how I can download files from it.

I hope someone can give me a Code example on that.

Connecting to FTP-Server:

function connect(Host, Username, Password : string) : boolean;
var
FTP: TFTPSend;
begin
FTP := TFTPSend.Create;

FTP.TargetHost := Host;
FTP.TargetPort := Port;
FTP.AutoTLS := true;
FTP.Username := username;
FTP.Password:= Password;
FTP.Login;

Solution

  • You can download a file thru TFTPSend.RetrieveFile function

    function RetrieveFile(const FileName: string; Restore: Boolean): Boolean; virtual;

    var
     FTP: TFTPSend;
    begin
      FTP := TFTPSend.Create;
      try
        ....
          FTP.DirectFileName := LocalPath;
          FTP.DirectFile     := True;
          FTP.RetrieveFile(RemotePath, True);
        ....
      finally
        FTP.Free;
      end;
    end;
    

    Also you can use this function FtpGetFile

    function FtpGetFile(const IP, Port, FileName, LocalFile, User, Pass: string): Boolean;


    Update To download all files in given directory you need to perform loop as below:

      FTP.DirectFile:=True;
      if FTP.List('', False) then
        for I := 0 to FTP.FtpList.Count-1 do begin
            FTP.DirectFileName := FTP.FtpList[I].FileName;
            FTP.RetrieveFile(FTP.FtpList[I].FileName, True);
        end;        
    

    Check TFTPSend.List for more information.