转载 ---新版 THttpClient组件同步下载文件方法。

本文章转自:http://blog.qdac.cc/?p=4165

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
//Queue运行在主线程中,且是异步的。
TThread.Queue(nil,
procedure
begin
ProgressBar1.Position := AReadCount;
end);
end;

procedure TForm3.btnStartClick(Sender: TObject);
begin
//创建一个普通线程,防止界面假死.
TThread.CreateAnonymousThread(
procedure
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).Start;
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.

 

posted @ 2016-08-29 10:49  熊大熊二  阅读(134)  评论(0编辑  收藏  举报