实际上我正在使用TIdHTTP组件从互联网上下载文件。我想知道是否可能暂停并使用此组件恢复下载o或许是另一个indy组件。
这是我当前的代码,这适用于下载文件(没有恢复),但是。现在我想暂停下载关闭我的应用程序,当我的应用程序重新启动时,从最后保存的位置恢复下载。
var
Http: TIdHTTP;
MS : TMemoryStream;
begin
Result:= True;
Http := TIdHTTP.Create(nil);
MS := TMemoryStream.Create;
try
try
Http.OnWork:= HttpWork;//this event give me the actual progress of the download process
Http.Head(Url);
FSize := Http.Response.ContentLength;
AddLog('Downloading File '+GetURLFilename(Url)+' - '+FormatFloat('#,',FSize)+' Bytes');
Http.Get(Url, MS);
MS.SaveToFile(LocalFile);
except
on E : Exception do
Begin
Result:=False;
AddLog(E.Message);
end;
end;
finally
Http.Free;
MS.Free;
end;
end;
答案 0 :(得分:5)
以下代码对我有用。它按块下载文件:
procedure Download(Url,LocalFile:String;
WorkBegin:TWorkBeginEvent;Work:TWorkEvent;WorkEnd:TWorkEndEvent);
var
Http: TIdHTTP;
exit:Boolean;
FLength,aRangeEnd:Integer;
begin
Http := TIdHTTP.Create(nil);
fFileStream:=nil;
try
try
Http.OnWork:= Work;
Http.OnWorkEnd := WorkEnd;
Http.Head(Url);
FLength := Http.Response.ContentLength;
exit:=false;
repeat
if not FileExists(LocalFile) then begin
fFileStream := TFileStream.Create(LocalFile, fmCreate);
end
else begin
fFileStream := TFileStream.Create(LocalFile, fmOpenReadWrite);
exit:= fFileStream.Size >= FLength;
if not exit then
fFileStream.Seek(Max(0, fFileStream.Size-4096), soFromBeginning);
end;
try
aRangeEnd:=fFileStream.Size + 50000;
if aRangeEnd < fLength then begin
Http.Request.Range := IntToStr(fFileStream.Position) + '-'+ IntToStr(aRangeEnd);
end
else begin
Http.Request.Range := IntToStr(fFileStream.Position) + '-';
exit:=true;
end;
Http.Get(Url, fFileStream);
finally
fFileStream.Free;
end;
until exit;
Http.Disconnect;
except
on E : Exception do
Begin
//Result:=False;
//AddLog(E.Message);
end;
end;
finally
Http.Free;
end;
end;
答案 1 :(得分:1)
也许HTTP RANGE标头可以帮到你。有关恢复HTTP下载的更多信息,请查看http://www.west-wind.com/Weblog/posts/244.aspx。
另请参阅此处https://forums.embarcadero.com/message.jspa?messageID=219481,了解有关同一主题的TIdHTTP相关讨论。