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.

相关阅读 >>

Delphi strtohexstr 字符串转换hex

Delphi twebbrowser:确定带有框架的页面何时完成

Delphi 字符串适宽处理

Delphi xe 取得 app 自己的版本号 (狠跨 4 个平台)

Delphi 颜色表

Delphi安装*.pas扩展名的控件

Delphi实现的sunday字符串搜索算法

Delphi 变体数组

Delphi 15位身份证号码转18位身份证号码

Delphi 备份恢复剪切板

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...