delphi 新版 THttpClient组件同步下载文件方法


unit Unit3;

interface

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

type
  TForm3 = class(TForm)
    btnStart: TButton;
    ProgressBar1: TProgressBar;
    edt1: TEdit;
    procedure btnStartClick(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure FormShow(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }

    /// <summary>
    /// 下载的时候不允许关闭窗体
    /// </summary>
    FAllowFormClose: Boolean;

    /// <summary>
    /// 接收数据事件
    /// </summary>
    procedure ReceiveDataEvent(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean);
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

procedure TForm3.ReceiveDataEvent(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean);
begin
  //加上这句界面不卡死.
  Application.ProcessMessages;
  ProgressBar1.Position := AReadCount;
end;

procedure TForm3.btnStartClick(Sender: TObject);
var
  MyHTTPClient: THTTPClient;
  MyHTTPResponse: IHTTPResponse;
  MyMemoryStream: TMemoryStream;
  downloadUrl: string;
begin
  MyHTTPClient := THTTPClient.Create;
  MyMemoryStream := TMemoryStream.Create;
  try
    btnStart.Enabled := False;
    FAllowFormClose := False;
    downloadUrl := Trim(edt1.Text);

    //获取文件的大小
    MyHTTPResponse := MyHTTPClient.Head(downloadUrl);
    ProgressBar1.Position := 0;
    ProgressBar1.Max := MyHTTPResponse.ContentLength;

    //开始下载,保存到本地
    MyHTTPClient.OnReceiveData := ReceiveDataEvent;
    MyHTTPResponse := MyHTTPClient.Get(downloadUrl, MyMemoryStream);
    if MyHTTPResponse.StatusCode = 200 then
    begin
      MyMemoryStream.SaveToFile('c:\aa.exe');
      ShowMessage('下载完成');
    end;
  finally
    MyHTTPClient.Free;
    MyMemoryStream.Free;
    //最终都允许关闭窗体
    btnStart.Enabled := True;
    FAllowFormClose := True;
  end;
end;

procedure TForm3.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  CanClose := FAllowFormClose;
end;

procedure TForm3.FormCreate(Sender: TObject);
begin
  ReportMemoryLeaksOnShutdown := True;
end;

procedure TForm3.FormShow(Sender: TObject);
begin
  btnStart.Enabled := True;
  FAllowFormClose := True;
  ProgressBar1.Position := 0;
end;

end.

联系电话:
020-00000000
联系电话:
020-00000000
联系电话:
020-12345678