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 开发安卓时判断进入非活动

Delphi如何简单取得后缀名

Delphi firedac 下的 sqlite 创建数据库

Delphi 三种方式读取txt文本文件

Delphi isvaliddatetime、isvaliddate、isvalidtime、isvaliddateday ... 判断时间是否合法

Delphi 简单实习窗体靠边隐藏

Delphi 递归遍历 treeview树节点

Delphi使用idhttp.get('') 造成假死(堵塞),请问线程idhttp怎么才能做到不出错?

Delphi切换指定窗口到最前并获得焦点

Delphi 得到指定文件夹内文件名

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



打赏

取消

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

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

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

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

评论

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