Delphi Indy TCPClient/TCPServer元件傳檔

Indy這套免費又強大的網路元件相信對Delphi開發者不陌生,不過常常被問如何透過Indy傳送檔案。
寫了個簡單的範例給大家。

一、伺服端
只需要在表單放上一個IdTCPServer元件,接著在FormOnCreate以及IdTCPServer1OnExecute寫上
[pascal]
procedure TForm1.FormCreate(Sender: TObject);
begin
idtcpserver1.DefaultPort := 1234; // 可自行更改Port號,但Client/Server要一致
idtcpserver1.Active:=true;
end;

procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
ms:Tfilestream;
fn:String;
begin
fn := ExtractFileName(acontext.Connection.IOHandler.ReadLn()); // 從Client接收檔名
ms := Tfilestream.Create(‘c:\’+fn, fmCreate);
ms.Position :=0;
acontext.Connection.IOHandler.ReadStream(ms,0,true);
ms.Free;
end;
[/pascal]

二、客戶端
畫面上放上IdTCPClient外,再放上三個Edit(分別是EdtHost、EdtPort、EdtFileName)以及四個Button(分別是BtnConnect、BtnDisConnect、BtnChooseFile、BtnSend)以及一個OpenDialog
[pascal]
procedure TForm1.BtnConnectClick(Sender: TObject);
begin
// 連接到伺服器
if IdTCPClient1.Connected then
IdTCPClient1.Disconnect;
IdTCPClient1.Host := EdtHost.Text;
IdTCPClient1.Port := StrToInt(EdtPort.Text);
IdTCPClient1.Connect;
end;

procedure TForm1.BtnDisconnectClick(Sender: TObject);
begin
// 斷開連線
IdTCPClient1.Disconnect;
end;

procedure TForm1.BtnChooseFileClick(Sender: TObject);
begin
// 選擇檔案
if opendialog1.Execute then begin
EdtFileName.Text :=opendialog1.FileName;
end;
end;

procedure TForm1.BtnSendClick(Sender: TObject);
var
ms : tmemorystream;
begin
// 傳送檔案
BtnConnect.Click;
ms := Tmemorystream.Create;
ms.Clear;
ms.LoadFromFile(EdtFileName.Text);
ms.Position :=0;
IdTCPClient1.IOHandler.LargeStream := true;
idtcpclient1.IOHandler.WriteLn(ExtractFileName(EdtFileName.Text)); // 告知檔名
idtcpclient1.IOHandler.Write(ms);
idtcpclient1.IOHandler.Close; // 很重要的一行,不然傳送完,無法開啟會出現檔案使用中
ms.Free;
end;
[/pascal]

作者: 林壽山

目前任職於軟體公司研究開發部門,擔任專業處長,專注於.NET C# 開發,並具備豐富的POS 收銀系統與金流整合開發經驗。我精通各類支付系統的設計與開發,包含第三方支付(如綠界、藍新、歐付寶、速買配、馬來西亞 ePay/HappyPay、台新 One 碼)、行動支付(悠遊卡、一卡通、支付寶、微信支付、街口支付)、以及信用卡支付(聯合信用卡)。 熟悉多種開發技術,擅長PHP 網頁開發(CodeIgniter、Laravel 框架)、Delphi 程式設計、資料庫設計、C# WinForm/WebForm 應用開發、ASP.NET MVC、API 串接設計,並具備LINE 串接開發的豐富經驗。 除了技術開發之外,我也熱衷於技術分享,曾擔任台中學校產業學院講師 5 年,培育新一代的軟體開發人才,致力於推動軟體技術的應用與創新。 我對技術充滿熱忱,始終保持學習與探索的心態,期望透過軟體開發為企業與社會創造更大的價值。