Delphi NetHTTPClient1 下载显示进度条

unit untFrmDownFile;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Net.URLClient,
  System.Net.HttpClient, System.Net.HttpClientComponent, Vcl.ComCtrls,
  Vcl.StdCtrls;

type
  TFrmDown = class(TForm)
    NetHTTPClient1: TNetHTTPClient;
    ProgressBar1: TProgressBar;
    Label1: TLabel;
    procedure NetHTTPClient1RequestCompleted(const Sender: TObject;
      const AResponse: IHTTPResponse);
    procedure NetHTTPClient1ReceiveData(const Sender: TObject; AContentLength,
      AReadCount: Int64; var Abort: Boolean);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormShow(Sender: TObject);
  private
    { Private declarations }
    AResponse: TStringStream;
  public
    { Public declarations }
    FileName: string;

    procedure DoDownload(Url: string);
  end;

var
  FrmDown: TFrmDown;

implementation

{$R *.dfm}

//delphi 字节数转换为KB或MB字符串
function BytesToStr(iBytes: Integer): String;
var
  iKb: Integer;
begin
  iKb := Round(iBytes / 1024);
  if iKb > 1000 then
    Result := Format('%.2f MB', [iKb / 1024])
  else
    Result := Format('%d KB', [iKb]);
end;

procedure TFrmDown.DoDownload(Url: string);
begin
  AResponse.Clear;
  NetHTTPClient1.Get(Url,AResponse);
end;

procedure TFrmDown.FormCreate(Sender: TObject);
begin
  AResponse := TStringStream.Create('',TEncoding.UTF8);
end;

procedure TFrmDown.FormDestroy(Sender: TObject);
begin
  FreeAndNil(AResponse);
end;

procedure TFrmDown.FormShow(Sender: TObject);
begin
  ProgressBar1.Position := 0;
end;

procedure TFrmDown.NetHTTPClient1ReceiveData(const Sender: TObject;
  AContentLength, AReadCount: Int64; var Abort: Boolean);
begin
  ProgressBar1.Max := AContentLength;
  ProgressBar1.Position := AReadCount;
  Label1.Caption := BytesToStr(AReadCount) + ' / ' + BytesToStr(AContentLength);
end;

procedure TFrmDown.NetHTTPClient1RequestCompleted(const Sender: TObject;
  const AResponse: IHTTPResponse);
begin
  try
    if AResponse.ContentStream.Size > 0  then
    begin
      if FileExists(FileName) then
        DeleteFile(FileName);
      Self.AResponse.SaveToFile(FileName);
      Application.MessageBox('下载成功', '提示信息', MB_OK + MB_ICONINFORMATION);
      Self.Close;
    end;
  except
    Self.Close;
  end;
end;

end.

类似文章

发表回复

您的电子邮箱地址不会被公开。