Delphi Indy TCPClient/TCPServer元件傳檔

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

一、伺服端
只需要在表單放上一個IdTCPServer元件,接著在FormOnCreate以及IdTCPServer1OnExecute寫上

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;

二、客戶端
畫面上放上IdTCPClient外,再放上三個Edit(分別是EdtHost、EdtPort、EdtFileName)以及四個Button(分別是BtnConnect、BtnDisConnect、BtnChooseFile、BtnSend)以及一個OpenDialog

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;

Delphi 使用idhttp下載顯示進度列及檔案大小

downloadwithprocessbar

在更新程式時,需要知道目前下載到多少百分比及大小怎麼做?

在Delphi使用idhttp及IdAntiFreeze(防止程式看起來當掉)二個元件就可以做得到。順便列下關鍵程式碼

procedure TForm1.BtnDownloadClick(Sender: TObject);
var
  tStream: TMemoryStream;
begin
  tStream := TMemoryStream.Create;
  try
    IdHTTP1.Get(EdtSource.Text, tStream);
    tStream.SaveToFile(EdtTarget.Text);
    ShowMessage('Download Success!');
  except
    ShowMessage('Download Fail!');
  end;
  tStream.Free;
end;

procedure TForm1.IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  Label1.Caption := BytesToStr(aWorkCount);
  ProgressBar1.Position := aWorkCount;
  Update;
end;

procedure TForm1.IdHTTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCountMax: Int64);
begin
  ProgressBar1.Max := aWorkCountMax;  // Set File total size
  Label2.Caption := BytesToStr(aWorkCountMax);
  Update;
end;

Github原始碼下載 : https://github.com/superlevin/downloadwithprocessbar