狼行神码

导航

Delphi10.2 关于Http 下载

演示如图:

代码如下:

 1 unit Unit1;
 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, IdComponent, Vcl.ComCtrls, Vcl.StdCtrls,
 8   IdAntiFreezeBase, IdAntiFreeze, IdBaseComponent, IdTCPConnection, IdTCPClient,
 9   IdHTTP;
10 
11 type
12   TForm1 = class(TForm)
13     Label1: TLabel;
14     Label2: TLabel;
15     Edit1: TEdit;
16     Edit2: TEdit;
17     IdHTTP1: TIdHTTP;
18     IdAntiFreeze1: TIdAntiFreeze;
19     Button1: TButton;
20     ProgressBar1: TProgressBar;
21     Label3: TLabel;
22     Label4: TLabel;
23     Label5: TLabel;
24     Label6: TLabel;
25     procedure IdHTTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
26       AWorkCountMax: Int64);
27     procedure IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode;
28       AWorkCount: Int64);
29     procedure Button1Click(Sender: TObject);
30   private
31     { Private declarations }
32   public
33     { Public declarations }
34   end;
35 
36 var
37   Form1: TForm1;
38 
39 implementation
40 
41 {$R *.dfm}
42 //1. 字节数转换为KB或MB字符串
43 function BytesToStr(iBytes: Integer): String;
44 var
45   iKb: Integer;
46 begin
47   iKb := Round(iBytes / 1024);
48   if iKb > 1000 then
49     Result := Format('%.2f MB', [iKb / 1024])
50   else
51     Result := Format('%d KB', [iKb]);
52 end;
53 
54 procedure TForm1.IdHTTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
55   AWorkCountMax: Int64);
56 begin
57   ProgressBar1.Max := AWorkCountMax;                // 获取要下载的文件大小
58   Label2.Caption := BytesToStr(AWorkCountMax);
59   Update;
60 end;
61 
62 procedure TForm1.IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode;
63   AWorkCount: Int64);
64 begin
65   Label1.Caption := BytesToStr(aWorkCount);      //更新进度
66   ProgressBar1.Position := aWorkCount;           //更新进度条
67   Update;
68 end;
69 
70 
71 procedure TForm1.Button1Click(Sender: TObject);
72 
73 var
74   tStream: TMemoryStream;
75 begin
76   tStream := TMemoryStream.Create;
77   try
78     IdHTTP1.Get(Edit1.Text, tStream);       //保存到内存流 (下载链接)
79     tStream.SaveToFile(Edit2.Text);         //保存为文件  (路径)
80     ShowMessage('下载成功!');
81   except
82     ShowMessage('下载失败!');
83   end;
84   tStream.Free;
85 
86 end;
87 
88 
89 end.

 

posted on 2017-06-21 09:59  狼行神码  阅读(517)  评论(0编辑  收藏  举报