这是我用 IdTCP 做的一个下载(系统自动升级用)的例子(客户端)
Function FDownFile
(
AiFollow : pChar; //断点续传标志(T是/F否)
AiHost : pChar; //文件服务器主机IP
AiPort : Integer; //端口号
AiFileName : pChar; //传入文件名
AiSavePath : PChar; //下载后的文件存放路径
AoFileName : pChar; //传出文件名
AoMsg : pChar //提示信息
) : Integer; StdCall;
Var
sHost, sRemoteFile, sLocalFile, sSavePath : String;
IdAntiFreezeDown : TIdAntiFreeze;
IdTCPCDown : TIdTCPClient;
fStream : TFileStream;
Begin
Result := 1;
StrPCopy(AoMsg, '文件下载失败');
Try
sHost := StrPas(AiHost);
sRemoteFile := Trim(StrPas(AiFileName));
{
If StrRScan(AiSavePath, '/')<>'/' Then sSavePath := StrPas(AiSavePath) + '/'
Else sSavePath := StrPas(AiSavePath);
}
sSavePath := Trim(StrPas(AiSavePath)) + '/';
sSavePath := StringReplace(sSavePath, '//', '/', [rfReplaceAll]);
If Not DirectoryExists(sSavePath) Then ForceDirectories(sSavePath);
sLocalFile := sSavePath + ExtractFileName(sRemoteFile);
StrPCopy(AoFileName, sLocalFile);
If AiFollow<>'T' Then //'T'断点续传
If FileExists(sLocalFile) Then DeleteFile(sLocalFile);
Except
Exit;
End;
//
IdAntiFreezeDown := TIdAntiFreeze.Create(Nil);
IdTCPCDown := TIdTCPClient.Create(Nil);
Try
With IdTCPCDown Do
Begin
Disconnect;
Host := sHost;
Port := AiPort;
Connect;
WriteLn(_DownCommand + sRemoteFile);
End;
//
Try
fStream := TFileStream.Create(sLocalFile, fmCreate);
While IdTCPCDown.Connected Do
Begin
IdTCPCDown.ReadStream(fStream, -1, True);
End;
Except
On E:Exception Do
Begin
StrPCopy(AoMsg, '文件创建失败:' + E.Message);
Exit;
End;
End;
//
StrPCopy(AoMsg, '文件下载成功');
Result := 0;
Finally
If Assigned(fStream) Then FreeAndNil(fStream);
IdTCPCDown.Disconnect;
If Assigned(IdTCPCDown) Then FreeAndNil(IdTCPCDown);
FreeAndNil(IdAntiFreezeDown);
End;
End;