5

実際、私はインターネットからファイルをダウンロードするためにTIdHTTPコンポーネントを使用しています。このコンポーネントまたは別のインディコンポーネントを使用して、ダウンロードを一時停止して再開できるかどうか疑問に思っています。

これは私の現在のコードです。これは(履歴書なしで)ファイルをダウンロードするのに問題なく機能しますが、。ダウンロードを一時停止してアプリを閉じ、アプリを再起動したら、最後に保存した位置からダウンロードを再開します。

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;
4

2 に答える 2

6

次のコードは私にうまくいきました。ファイルをチャンクごとにダウンロードします。

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;
于 2010-07-20T09:19:10.587 に答える
1

たぶん、HTTPRANGEヘッダーがここであなたを助けることができます。HTTPダウンロードの再開の詳細については、 http://www.west-wind.com/Weblog/posts/244.aspxを参照してください。

同じトピックに関するTIdHTTP関連のディスカッションについては、https: //forums.embarcadero.com/message.jspa?messageID=219481も参照してください。

于 2010-06-03T08:25:55.720 に答える