var
Form2: TForm2;
implementation
var
AbortTransfer: Boolean;
aURL, aFile: string;
tcount: integer;
//检查文件是否全部下载完毕
{$R *.dfm}
//get FileName
function TForm2.GetURLFileName(aURL: string): string;
var
i: integer;
s: string;
begin
//返回下载地址的文件名
s := aURL;
i := Pos('/', s);
while i <> 0do
//去掉"/"前面的内容剩下的就是文件名了
begin
Delete(s, 1, i);
i := Pos('/', s);
end;
Result := s;
end;
//get FileSize
function TForm2.GetFileSize(aURL: string): integer;
var
FileSize: integer;
begin
IdHTTP1.Head(aURL);
FileSize := IdHTTP1.Response.ContentLength;
IdHTTP1.Disconnect;
Result := FileSize;
end;
//执行下载
procedure TForm2.Button1Click(Sender: TObject);
var
j: integer;
begin
tcount := 0;
Showmessage('OK!主线程在执行,获得文件名并显示在Edit2中');
aURL := Edit1.Text;
//下载地址
aFile := GetURLFileName(Edit1.Text);
//得到文件名
nn := StrToInt(Edit2.Text);
//线程数
j := 1;
aFileSize := GetFileSize(aURL);
avg := trunc(aFileSize / nn);
begin
try
GetThread();
while j <= nndo
begin
MyThread[j].Resume;
//唤醒线程
j := j + 1;
end;
except
Showmessage('创建线程失败!');
Exit;
end;
end;
end;
//退出程序
procedure TForm2.Button3Click(Sender: TObject);
begin
application.Terminate;
end;
//循环产生线程
procedure TForm2.GetThread();
var
i: integer;
start: array[1..100] of integer;
last: array[1..100] of integer;
//改用了数组,也可不用
fileName: string;
begin
i := 1;
while i <= nndo
begin
start := avg * (i - 1);
last := avg * i -1;
//这里原先是last:=avg*i;
if i = nn then
begin
last := avg*i + aFileSize-avg*nn;
//这里原先是aFileSize
end;
fileName := aFile + IntToStr(i);
MyThread := TThread1.create1(aURL, aFile, fileName, false, i, start,
last);
i := i + 1;
end;
end;
procedure TForm2.AddFile();
//合并文件
var
mStream1, mStream2: TMemoryStream;
i: integer;
begin
i := 1;
mStream1 := TMemoryStream.Create;
mStream2 := TMemoryStream.Create;
mStream1.loadfromfile(aFile + '1');
while i < nndo
begin
mStream2.loadfromfile(aFile + IntToStr(i + 1));
mStream1.seek(mStream1.size, soFrombegin
ning);
mStream1.copyfrom(mStream2, mStream2.size);
mStream2.clear;
i := i + 1;
end;
mStream2.free;
mStream1.SaveToFile(aFile);
mStream1.free;
//删除临时文件
i:=1;
while i <= nndo
begin
deletefile(aFile + IntToStr(i));
i := i + 1;
end;
Form2.ListBox1.ItemIndex := Form2.ListBox1.Items.Add('下载成功');
end;
procedure TThread1.Execute;
begin
if Form2.Edit1.Text <> '' then
//synchronize(DownLodeFile)
do
wnLodeFile
else
exit;
inc(tcount);
if tcount = Form2.nn then
//当tcount=nn时代表全部下载成功
begin
//Showmessage('全部下载成功!');
Form2.ListBox1.ItemIndex := Form2.ListBox1.Items.Add('正在合并删除临时文件');
Form2.AddFile;
end;
end;