Many applications now need to upload and download large files, and have certain limitations in the HTTP mode. Fortunately, FTP as a very old and very mature protocol can efficiently and stably complete the upload download of big files, and can perfectly achieve renewal. Take the movie server management server that I wrote. After the various programs are compared, I found that the FTP can perfectly implement the requirements. But to achieve FTP through the Winsocket library, Fortunately, there is Indy - a component package that packages most of the network protocols.
With Indy, the programming staff can program by blocking, and can throw away the Winsocket asynchronous mode, using the equivalent block programming mode on the UNIX system. In this way, the programmer can process the running process of the program.
Below, we have entered Indy's TIDFTP world.
1. Description of the control
Using the TIDFTP control in Indy 9, you can implement the upload and download of files through the FTP mode.
2. Specific use of the control
(1) Control property settings
The default properties can be set directly related to the server connection, such as the host name, such as the host name, is set when the connection is established. It is necessary to set the value of the two attributes of RecvBuffersize and SendBuffersize. In addition, the TRANSFERTYPE attribute needs to be specified according to the type of file to be transmitted, and other properties are set according to the default value.
Recvbuffersize Description (The default is 8192 bytes): This property is an integer variable, which is used to specify the acceptance buffer size used for the connection.
SendBuffersize Description (Default is 32768 bytes): This property is also an integer variable, which is used to specify the maximum value of the send buffer used by the connection. This property can be used for TSTREAM to specify the number of blocks to send content in the WritestReam method. If the content to be transmitted is greater than this attribute value, the sending content is divided into multiple blocks.
TRANSFERTYPE Description (default is ftbinary): This property is the TIDFTPTRANSFERTYPE type variable. The use of the transfer content is a binary (ftbinary) or an ASCII file (FTASCII). The application needs to transmit executable files, compressed files, and multimedia files, etc. in binary mode; use ASCII mode to transmit text or hypervisor text data.
(2) Event response of the control
OnDisconnected response: TNOTIFYEVENT class, used to respond to disconnect events. When the disconnect method is called to close the socket, it triggers the response. The application must specify the process of the event response to make the disconnect event.
OnStatus response: TidStatusevent class. This response is triggered when the currently connected state changes. This event can be triggered by the Dostatus method and supplied to the event controller properties. AxStatus is the currently connected TidStatus value; Aaargs is an optional parameter for formatting functions, which will construct a text message that represents the current connection status.
ONWORK response: Onword is the response controller of the Tortevent class event. ONWORK is used to associate a DOWORK method to notify Indy components and classes when the buffer read and write operation is called. It is generally used to control updates for progress bars and window elements. AWorkMode represents the current mode of operation, where the WMREAD-component is reading data; the WMWRITE-component is sending data. AWORKCOUNT indicates the currently operated byte count.
ONWORKBEGIN response: TWORKBEGINEVENT class. This event is used to notify Indy components and classes when the buffer read and write operation is initialized. It is generally used to control updates for progress bars and window elements. AWorkMode represents the current mode of operation, where the WMREAD-component is reading data; the WMWRITE-component is sending data. AWORKCountmax is used to indicate the maximum number of bytes that is sent to the ONWORKBEGIN event, and 0 value represents unknown. ONWORKEND response: TWORKENDEVENT class. This event is used to notify the IND components and classes when the buffer read / write operation terminates. AWorkMode represents the current mode of operation, where the WMREAD-component is reading data; the WMWRITE-component is sending data. AWORKCOUNT indicates the number of bytes of operation.
In an event response, the program is mainly controlled by the above five event responses. In general, set the interface notification disconnected in OnDisconnected; set the status of the current operation in onStatus; implement the status strips and other parameters in the transfer in ONWORK; and set in ONWORKBEGIN and ONWORKEND Start the interface at the end of the transmission and transfer.
(3) Connect the remote server
After completing the setting control property and the event response that implements the control, you can interact and transfer with the server. Before the connection, it should first determine if the IDFTP is in connection state. If the connection is false, the settings of some TCP class properties associated with the server connection are specified by the interface control or other means, respectively: Host (host name): string, username (User Name): String, Password (Password): String, you can also specify port. After the Connect method is then called to connect the remote server. If there is no abnormality, the connection is successfully established.
Procedure Description: Procedure Connect (AAUTOLOGIN: Boolean; Const Atimeout: Integer);
This process connection remote FTP server
Property: AAUTOLOGIN: Boolean = TRUE
After the connection is automatically logged in, this parameter is default to true.
Const atimeout: integer = idtimeoutdefault
Timeout, unit: second.
Sample code:
if idftp1.connected the THEN
IF transferrigndata damftp1.abort;
Idftp1.quit;
Finally
end
Else with idftp1 do try
Username: = useridedit.text;
Password: = passwordedit.text;
Host: = ftpserveredit.text;
CONNECT;
Changedir (currentdiRedit.text);
Finally
END;
(4) Change the directory
After the connection is established, you can change the current FTP session. For the known absolute path, you can directly call the ChangeDir (const adirname: string) method to convert the directory, and adiRName represents the file system directory on the server, and can also call ChangeDirup to go back to the upper directory.
If the path is unknown, you can obtain the current directory structure of the remote server through list (ADest: TSTRINGS; Const ASPECIFIER: STRING; Const Adetails: Bolean), you must set TransforType to ftascii (ASCII mode), where: ADest saves the current The directory structure can call this list in subsequent programs. You can also get the current directory name through the RetrieVecurrentDir method. Process Description:
Procedure Changedir (const adirname: string);
Change the work catalog
Attributes
Const adirname: String
Directory description of the remote server
Description: This process is actually an FTP CWD command.
PROCEDURE CHANGEDIRUP;
To the previous directory
Function RetrieVecurrentdir: String;
This function returns the current directory name
Procedure List (ADest: Tstrings; Const Aspecifier: String; Const Adetails: Boolean;
List all files and subdirectories of the current directory and its properties
parameter:
ADest: Tstrings
Save the file and subdirectory return results
Const aspecifier: String = ''
File mask for listing the qualified file
Const Adetails: Boolean = TRUE
Contains files and subdirectory properties
Property DirectoryListing: TIDFTPLISTITISTING;
Returns a list of files and directory structures
Sample code:
Ls: = TSTRINGLIST.CREATE
Try
IDftp1.changedir (DIRNAME);
Idftp1.transfertype: = ftascii;
CurrentDiredit.text: = idftp1.RetrieVecurrentdir;
DirectoryListBox.Items.clear;
Idftp1.list (ls);
DirectoryListBox.Items.Assign (LS);
If DirectoryListBox.Items.count> 0 THEN
IF ANSIPOS ('Total', DirectoryListBox.items [0])> 0 Then DirectoryListBox.Items.delete (0);
Finally
Ls.free;
END;
(5) Download implementation
Before downloading, you must view DirectoryListing.Items [scurrfile] .ITEMTYPE is file, if you return to DITDIRECTORY, represent the current file name, you can't download, must be directed to the file. If you are file, you can download it. Before downloading, set the type of transfer to the binary, and specify the path to which you want to save. Implement the download of the file by calling the GET method. The download process is slower and can be considered to put it in the thread.
Process Description:
Procedure get (const asource: string; adst: tstream; aresume: boolean); overload;
Procedure GET (Const Asourcefile: String; Const ADestfile: String; Const AcanoverWrite: Boolean; ARESUME: BOOLEAN); OVERLOAD
Get files from the remote server.
Property Description: Const AsourceFile: String
Source text name on the remote server
Const ADestFile: String
Save the file name on the client
Const AcanoverWrite: Boolean = FALSE
Rewrite the same name file
Aresume: Boolean = FALSE
Whether it makes a breakpoint
Sample code:
Savedialog1.filename: = name;
if Savedialog1.execute Then Begin
SetFunctionButtons (false);
Idftp1.transfertype: = ftbinary;
BYTESTORANSFER: = idftp1.size (name);
If FileExists (Name) THEN Begin
Case Messagedlg ('file aready exissrs. Do you want to resume the download operation?',
MTConfirmation, Mbyesnocancel, 0) of
MRYES: Begin
Bytestotransfer: = bytestotransfer - FileSizeByName (Name);
Idftp1.get (name, savedialog1.filename, false, true);
END;
MRNO: Begin
Idftp1.get (name, savedialog1.filename, true);
END;
Mrcancel: Begin
EXIT;
END;
END;
end
Else Begin
Idftp1.get (name, savedialog1.filename, false);
END;
(6) Upload implementation
Upload implementation is similar to the download, can be passed through the PUT method.
Process Description:
Procedure Put (Const ASource: TSTREAM; Const ADestfile: String; Const AAPPEND: Boolean; OVERLOAD;
Procedure Put (const asourcefile: string; const); constrapen; boolean; overload;
Upload file to server
Property Description:
Const asourcefile: String
The file to be uploaded
Const ADestFile: String = ''
Target file name on the server
Const aAppend: boolean = false
Will it continue to upload?
Code example:
if idftp1.connected the begin
IF uploadopendialog1.execute the THEN
Idftp1.transfertype: = ftbinary;
Idftp1.put (Uploadopendialog1.FileName);
/ / Can add a change in the directory you can add;
Finally
/ / Complete clear work
END;
END;
(7) Remove the implementation
Deleting a file Using the Delete method, the method deletes the specified file, and the object must be a file. Use the RemoveDir method if you want to delete a directory.
Process Description:
Procedure delete (const AfileName: String);
Delete Files
Procedure Removedir (const adirname: string);
Delete the folder, delete the folder according to different servers has different requirements. Some servers do not allow deletion of non-empty folders, and programmers need to add the code of the empty directory. The parameters of the above two processes are the target name
Code example:
IF not idftp1.connected kil
Name: = idftp1.directoryListing.Items [icrrsect] .filename;
If idftp1.directoryListing.Items [icrrsect] .ItemType = DITDIRECTORY THEN THEN
Idftp1.removedir (name);
Finally
end
Else
Try
Idftp1.delete (name);
Finally
END;
(8) Realization of the back
The retreat is actually one of the directory operations, and it can be achieved simply to achieve the current directory as .. can also be implemented by returning to the superior directory.
(9) Cancellation implementation
During the transfer of IDFTP, you can use the Abort method to cancel the current operation at any time. The implementation of the ONWORK event is to determine when to cancel the operation.
Code example:
// Cancel button on the onclick response
Procedure TMAINFORM.ABORTBUTTONCLICK (Sender: TOBJECT);
Begin
Aborttransfer: = true;
END;
// IDFTP's ONWORK event response
Procedure TMAINFORM.IDFTP1WORK (Sender: TOBJECT; AWORKMODE: TWORKMODE;
Const aworkcount: integer;
Begin
...
IF Aborttransfer dam.
Aborttransfer: = false;
END;
(10) Realization of breakpoint resume
The breakpoint renewal is to determine if the transferred file is overloaded at the beginning of the upload or download process, and if the transfer is not completed, the transfer work is continued at the last interrupt. Achieving this function requires two important operations, first is the size information of the judgment file, followed by specifying uploaded behavior in the transmission process GET and PUT.
Determine the size of the file using the function size (filename) on the server. In the download process, compare the information of local files and remote files, and then specify Aresume: = true in GET. Like upload, specify the AAPPEND: = TRUE of the PUT.
In the front, we have talked, Indy's network operation is mostly blocking mode, and TIDFTP is no exception. This is temporarily frozen when the user interface is temporarily frozen during the above-described various operational operations. So in actual programming, you need to use multithreaded way to ensure the response of the user. The Windows system can use the CreateTHread system call to create threads, but developers need to do lots of additional work to ensure synchronization of threads during use. In Indy, it also contains the control TidThreadComponent that implements multi-threaded control, which is more convenient when the control is more convenient than the control. I will introduce the use of TidthreadComponent in subsequent articles.
My email is: hubert@sina.com, please contact me if you have any questions.