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

downloadwithprocessbar

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

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

[pascal]
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;

[/pascal]

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