2010-06-03 86 views
5

實際上,我使用TIdHTTP組件從互聯網下載文件。我想知道是否有可能暫停並恢復使用這個組件的下載o也許是另一個indy組件。使用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; 

回答

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;