Delphi ftp upload files directory
Written by Codes Tips on April 25, 2009 – 2:56 pm -To upload files from a directory in delphi to a ftp server you should first loop through all the files that are in that directory. To do this you should first declare a new type of files, that will be a string of array that will hold the names of files from that directory.
type FilesArray=array[1..1000] of string;
To get all the files from a directory you should use the function FindFirst and FindNext to loop through all the files of directory. To use those functions you should include the unit SysUtils in the uses. To get the attribute of a file you should use the record TSearchRec.The TSearchRec record has the following attribute:
type TSearchRec = record Time : Integer; Size : Integer; Attr : Integer; Name : TFileName; ExcludeAttr : Integer; FindHandle : THandle; FindData : TWin32FindData; end;
The most impostant attributes you need are the following:
Time - when the file was last modified
Size - the size of the file
Attr - file attributes
Name - the name of the file
Here is the function to get all the files from a directory:
function GetFiles(dirpath:string;var nrfiles:integer):FilesArray; var searchResult : TSearchRec; allfiles: FilesArray; begin nrfiles:=0; if FindFirst(dirpath+'*.*', faAnyFile, searchResult) = 0 then begin repeat if (searchresult.name<>'.') and (searchresult.name<>'..') then begin inc(nrfiles); allfiles[nrfiles]:=searchresult.name; end; until FindNext(searchResult) <> 0; FindClose(searchResult);//free the memory GetFiles:=allfiles; end; end;
To upload a file to a ftp server we can use the ftp Indy component IdFtp, using the Put command to upload a file. In order not the application to stop when the file is uploaded use a try except statement to catch the error:
procedure UploadFiles(host:string;username:string;password:string); var files:FilesArray; j,nrfiles:integer; idftp1:TIdFtp; begin //conect to ftp server idftp1.Host:=host; idftp1.Username:=username; idftp1.Password:=password; idftp1.Connect; //go in which directory you need with ChangeDir command idftp1.ChangeDir('www'); //get all files from local dir files:=Getfiles(ExtractFilePath(application.exename)+'mydir\',nrfiles); //upload all files from dir to ftp server for j:=1 to nrfiles do begin idftp1.put(ExtractFilePath(application.exename) + 'mydir\' + files[j], files[j]); except On E:Exception do begin end; end; end; //disconnect from ftp server idftp1.Quit; end;
Tags: borland delphi, Delphi
Posted in Codes, Delphi |
Leave a Comment
You must be logged in to post a comment.


















