Asp.net TIDFtp usage

Source: Internet
Author: User
Tags remote ftp server

1. Connect to the remote server
Procedure Connect (AAutoLogin: boolean; const ATimeout: Integer );
2. Change the Directory
Procedure ChangeDir (const ADirName: string );
3 download
Procedure Get (const ASourceFile: string; ADest: TStream; AResume: Boolean); overload;
Procedure Get (const ASourceFile: string; const ADestFile: string; const ACanOverwrite: boolean; AResume: Boolean); overload;
4. Upload
Procedure Put (const ASource: TStream; const ADestFile: string; const AAppend: boolean); overload;
Procedure Put (const ASourceFile: string; const ADestFile: string; const AAppend: boolean); overload;
5. Delete
Procedure Delete (const AFilename: string );


Determine whether to connect
If IdFTP1.Connected then
Begin
...........
End;

Reference others for future notes

Currently, many applications need to upload and download large files. Uploading large files through HTTP has certain limitations. Fortunately, FTP, as a very old and mature protocol, can efficiently and stably upload and download large files, and can be perfectly resumed. Taking the movie server management program I wrote as an example, after comparing various solutions, I found that FTP can perfectly meet the requirements. However, it is troublesome to implement FTP through the WinSocket library. Fortunately, there is Indy, a component package that encapsulates most network protocols.
With Indy, program designers can program through blocking mode, and discard the poor Winsocket asynchronous mode, using the same blocking programming mode as on Unix systems. In this way, the programmer can well process the running process of the program.
Next, we enter the Indy TIdFtp world.

1. Control description

You can use the TIdFtp control in Indy 9 to upload and download files through FTP.

2. Specific Use of controls

(1) control property settings

You can set the default attributes that are directly related to server connections, such as host names and users. You must set the values of the RecvBufferSize and SendBufferSize attributes. In addition, you must specify the TransferType Attribute Based on the file type to be transferred, and set other attributes by default.

RecvBufferSize description (default value: 8192 bytes): This attribute is an integer variable used to specify the size of the buffer accepted by the connection.

SendBufferSize description (default value: 32768 bytes): This attribute is also an integer variable, used to specify the maximum value of the sending buffer used by the connection. This attribute can be used in the WriteStream method to specify the number of parts to be sent by TStream. If the content to be sent is greater than the attribute value, the sent content is divided into multiple sending blocks.

TransferType description (default value: ftBinary): This attribute is a TIdFTPTransferType variable. Specifies whether the transmitted content is a binary file (ftBinary) or an ASCII file (ftASCII ). Applications need to transmit executable files, compressed files, and multimedia files in binary mode, while text data such as text or hypertext is transmitted in ASCII mode.

(2) control Event Response

OnDisconnected response: tpolicyevent class, used to respond to disconnect events. This response is triggered when the Disconnect method is called to close the Socket. The application must specify the event response process to respond to the disconnection event.

OnStatus response: TIdStatusEvent class. This response is triggered when the status of the current connection changes. This event can be triggered by the DoStatus method and provided to the event controller attributes. AxStatus is the TIdStatus value of the current connection. aaArgs is an optional parameter used for formatting functions. It is used to construct text messages that represent the current connection status.

OnWork response: OnWord is the response controller for TWorkEvent events. OnWork is used to associate the DoWork method to notify Indy components and classes when buffer read/write operations are called. It is generally used to control the update of progress bars and window elements. AWorkMode indicates the current operation mode. The wmRead component is reading data, and the wmWrite component is sending data. AWorkCount indicates the byte count of the current operation.

OnWorkBegin response: TWorkBeginEvent class. When the buffer read/write operation is initialized, this event is associated with the BeginWork method to notify Indy components and classes. It is generally used to control the update of progress bars and window elements. AWorkMode indicates the current operation mode. The wmRead component is reading data, and the wmWrite component is sending data. AWorkCountMax indicates the maximum number of bytes of the Operation sent to the OnWorkBegin event. The value 0 indicates that the operation is unknown.

OnWorkEnd response: TWorkEndEvent class. When the buffer read/write operation ends, the event is associated with the EndWork method to notify Indy components and classes. AWorkMode indicates the current operation mode. The wmRead component is reading data, and the wmWrite component is sending data. AWorkCount indicates the number of bytes of the operation.

In Event Response, the program is mainly controlled through the above five event responses. In general, set the interface notification for disconnection in OnDisconnected; set the status of the current operation in OnStatus; display status entries and other parameters during transmission in OnWork; in OnWorkBegin and OnWorkEnd, set the interface at the start of transmission and end of transmission respectively.

(3) connect to the remote server

After setting the control properties and implementing the Event Response of the control, you can interact and transmit with the server. Before connecting, you should first determine whether IdFtp is in the connection state. If Connected is False, you can specify the settings of TCP properties related to server connection through interface controls or other methods, are: Host (Host name): String, Username (Username): String, Password (Password): String, you can also specify the Port ). Call the Connect method to Connect to the remote server. If no exception occurs, the connection is established successfully.

Process description: procedure Connect (AAutoLogin: boolean; const ATimeout: Integer );

This process connects to the remote FTP Server

Attribute: AAutoLogin: boolean = True

Automatically log on after connection. The default value is True.

Const ATimeout: Integer = IdTimeoutDefault

Timeout time, in seconds.

Sample Code:

If IdFTP1.Connected then try

If TransferrignData then IdFTP1.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 directory of the current FTP session. If the absolute path is known, you can directly call the ChangeDir (const ADirName: string) method to convert the directory. ADirName indicates the file system directory on the server, you can also call ChangeDirUp to return to the parent directory.

If the path is unknown, you can obtain the current directory structure of the remote server through the List (ADest: TStrings; const ASpecifier: string; const ADetails: boolean) process, in this case, the TransferType must be set to ftASCII (ASCII mode), where: ADest stores the current directory structure and can be called in subsequent programs. In addition, you can use the RetrieveCurrentDir method to obtain the current directory name.

Process description:

Procedure ChangeDir (const ADirName: string );

Change working directory

Attribute

Const ADirName: string

Remote Server Directory description

Note: This process actually implements the ftp cwd command.

Procedure ChangeDirUp;

To the upper-level 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 in the current directory and their attributes

Parameters:

ADest: TStrings

Save the returned results of files and subdirectories

Const ASpecifier: string =

File mask used to list eligible files

Const ADetails: boolean = true

Contains file and subdirectory attributes

Property DirectoryListing: TIdFTPListItems;

Returns the list of objects and directories.

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 check whether DirectoryListing. Items [sCurrFile]. ItemType is a file. If ditDirectory is returned, the current file name is a directory and cannot be downloaded. It must be directed to the file. If it is an object, you can download it. Before downloading, set the transmission type to binary and specify the path to be saved locally. You can call the Get method to download an object. The download process is slow. You can put it in the thread for implementation.

Process description:

Procedure Get (const ASourceFile: string; ADest: TStream; AResume: Boolean); overload;

Procedure Get (const ASourceFile: string; const ADestFile: string; const ACanOverwrite: boolean; AResume: Boolean); overload;

Obtain files from a remote server.

Attribute description:

Const ASourceFile: string

Source file name on the remote server

Const ADestFile: string

File name saved to the client

Const ACanOverwrite: boolean = false

Rewrite a file with the same name

AResume: Boolean = false

Indicates whether resumable data transfer is performed.

Sample Code:

SaveDialog1.FileName: = Name;

If SaveDialog1.Execute then begin

SetFunctionButtons (false );

IdFTP1.TransferType: = ftBinary;

BytesToTransfer: = IdFTP1.Size (Name );

If FileExists (Name) then begin

Case MessageDlg (File aready exists. Do you want to resume the download operation ?,

MtConfirmation, mbYesNoCancel, 0)

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

The upload implementation is similar to the download. You can use the put method.

Process description:

Procedure Put (const ASource: TStream; const ADestFile: string; const AAppend: boolean); overload;

Procedure Put (const ASourceFile: string; const ADestFile: string; const AAppend: boolean); overload;

Upload files to the server

Attribute description:

Const ASourceFile: string

File to be uploaded

Const ADestFile: string =

Target file name on the server

Const AAppend: boolean = false

Continue upload?

Sample Code:

If IdFTP1.Connected then begin

If UploadOpenDialog1.Execute then try

IdFTP1.TransferType: = ftBinary;

IdFTP1.Put (UploadOpenDialog1.FileName, ExtractFileName (UploadOpenDialog1.FileName ));

// You can add code for Directory change here;

Finally

// Complete cleanup

End;

End;

(7) Implementation of Deletion

The Delete method is used to Delete a specified object. The object to be deleted must be a file. If you want to delete a directory, use the RemoveDir method.

Process description:

Procedure Delete (const AFilename: string );

Delete an object

Procedure RemoveDir (const ADirName: string );

To delete folders, you must delete folders on different servers. Some servers do not allow deletion of non-empty folders. Programmers need to add code to clear directories.

The parameters of the preceding two processes are the target names.

Sample Code:

If not IdFTP1.Connected then exit;

Name: = IdFTP1.DirectoryListing. Items [iCurrSelect]. FileName;

If IdFTP1.DirectoryListing. Items [iCurrSelect]. ItemType = ditDirectory then try

Idftp1.RemoveDir (Name );

Finally

End

Else

Try

Idftp1.Delete (Name );

Finally

End;

(8) Implementation of rollback

Rollback is actually a type of directory operation. You can simply change the current directory to... or return to the parent directory.

(9) Implementation of Cancellation

During IdFtp transmission, you can use the abort method to cancel the current operation at any time. The OnWork event can be implemented to determine when to cancel the operation.

Sample Code:

// The OnClick response of the cancel button

Procedure TMainForm. AbortButtonClick (Sender: TObject );

Begin

AbortTransfer: = true;

End;

// IdFTP OnWork Event Response

Procedure TMainForm. IdFTP1Work (Sender: TObject; AWorkMode: TWorkMode;

Const AWorkCount: Integer );

Begin

...

If AbortTransfer then IdFTP1.Abort;

AbortTransfer: = false;

End;

(10) Implementation of resumable Data Transfer

Resumable data transfer starts when the upload or download process starts. It determines whether the transmitted file has been transmitted. if the transfer is not completed successfully, it continues at the last interruption. This function requires two important operations: first, determining the file size information, and second, specifying the upload behavior in the Get and Put processes.

The function Size (FileName) is used to determine the file Size on the server ). During the download process, compare the information of the local and remote files, and then specify AResume: = True in Get. The same applies to upload. You can specify the Put AAppend: = True.

As we have mentioned earlier, most of Indy's network operations are in blocking mode, and TIdFtp is no exception. In this way, the user interface is temporarily frozen during the above operations. You must wait for the call to return before continuing to respond to the user operation interface. Therefore, in actual programming, multithreading is required to ensure the user interface response. In Windows, you can use CreateThread to create threads. However, when using CreateThread, developers need to do a lot of extra work to ensure thread synchronization. Indy also includes the TIdThreadComponent that implements multithreading, which is more convenient and easier to control compared with the multi-thread control. I will introduce how to use TIdThreadCOmponent in subsequent articles.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.