转载
1 unit Unit3; 2 3 interface 4 5 uses 6 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, 7 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Net.HttpClient, 8 Vcl.ComCtrls; 9 10 type 11 TForm3 = class(TForm) 12 btnStart: TButton; 13 ProgressBar1: TProgressBar; 14 edt1: TEdit; 15 procedure btnStartClick(Sender: TObject); 16 procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); 17 procedure FormShow(Sender: TObject); 18 procedure FormCreate(Sender: TObject); 19 private 20 { Private declarations } 21 22 /// <summary> 23 /// 下载的时候不允许关闭窗体 24 /// </summary> 25 FAllowFormClose: Boolean; 26 27 /// <summary> 28 /// 接收数据事件 29 /// </summary> 30 procedure ReceiveDataEvent(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean); 31 public 32 { Public declarations } 33 end; 34 35 var 36 Form3: TForm3; 37 38 implementation 39 40 {$R *.dfm} 41 42 procedure TForm3.ReceiveDataEvent(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean); 43 begin 44 //Queue运行在主线程中,且是异步的。 45 TThread.Queue(nil, 46 procedure 47 begin 48 ProgressBar1.Position := AReadCount; 49 end); 50 end; 51 52 procedure TForm3.btnStartClick(Sender: TObject); 53 begin 54 //创建一个普通线程,防止界面假死. 55 TThread.CreateAnonymousThread( 56 procedure 57 var 58 MyHTTPClient: THTTPClient; 59 MyHTTPResponse: IHTTPResponse; 60 MyMemoryStream: TMemoryStream; 61 downloadUrl: string; 62 begin 63 MyHTTPClient := THTTPClient.Create; 64 MyMemoryStream := TMemoryStream.Create; 65 try 66 btnStart.Enabled := False; 67 FAllowFormClose := False; 68 downloadUrl := Trim(edt1.Text); 69 70 //获取文件的大小 71 MyHTTPResponse := MyHTTPClient.Head(downloadUrl); 72 ProgressBar1.Position := 0; 73 ProgressBar1.Max := MyHTTPResponse.ContentLength; 74 75 //开始下载,保存到本地 76 MyHTTPClient.OnReceiveData := ReceiveDataEvent; 77 MyHTTPResponse := MyHTTPClient.Get(downloadUrl, MyMemoryStream); 78 if MyHTTPResponse.StatusCode = 200 then 79 begin 80 MyMemoryStream.SaveToFile('c:\aa.exe'); 81 ShowMessage('下载完成'); 82 end; 83 finally 84 MyHTTPClient.Free; 85 MyMemoryStream.Free; 86 //最终都允许关闭窗体 87 btnStart.Enabled := True; 88 FAllowFormClose := True; 89 end; 90 end).Start; 91 end; 92 93 procedure TForm3.FormCloseQuery(Sender: TObject; var CanClose: Boolean); 94 begin 95 CanClose := FAllowFormClose; 96 end; 97 98 procedure TForm3.FormCreate(Sender: TObject); 99 begin 100 ReportMemoryLeaksOnShutdown := True; 101 end; 102 103 procedure TForm3.FormShow(Sender: TObject); 104 begin 105 btnStart.Enabled := True; 106 FAllowFormClose := True; 107 ProgressBar1.Position := 0; 108 end; 109 110 end. 111 11