Downloading a file in Delphi

后端 未结 3 993
夕颜
夕颜 2020-12-14 19:54

A google search shows a few examples on how to download a file in Delphi but most are buggy and half of the time don\'t work in my experience.

I\'m looking for a si

3条回答
  •  隐瞒了意图╮
    2020-12-14 20:41

    Why not make use of indy. If you use the TIdHTTP its simple

    procedure DownloadFile;    
    var
      IdHTTP1: TIdHTTP;
      Stream: TMemoryStream;
      Url, FileName: String;
    begin    
      Url := 'http://www.rejbrand.se';
      Filename := 'download.htm';
    
      IdHTTP1 := TIdHTTP.Create(Self);
      Stream := TMemoryStream.Create;
      try
        IdHTTP1.Get(Url, Stream);
        Stream.SaveToFile(FileName);
      finally
        Stream.Free;
        IdHTTP1.Free;
      end;
    end;
    

    You can even add a progress bar by using the OnWork and OnWorkBegin Events

    procedure IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode;AWorkCountMax: Int64);
    begin
      ProgressBar.Max := AWorkCountMax;
      ProgressBar.Position := 0;
    end;
    
    procedure IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
    begin
      ProgressBar.Position := AWorkCount;
    end;
    

    I'm not sure if these event fire in the context of the main thread, so any updates done to VCL components may have to be done using the tidnotify component to aviod threading issues. Maybe someone else can check that.

提交回复
热议问题