Why does the label not show download percentage while downloading a file with Indy?

Viewed 84

I have assigned AWorkCount value to ProgressBar.Position value like this:

procedure TfrmDosyaİndirmeProgramı.indyDosyaİndiriciWork(ASender: TObject;
  AWorkMode: TWorkMode; AWorkCount: Int64);
begin
  pbİndirmeGöstergesi.Position := AWorkCount;

lblİndirmeYüzdesi is Download Percantage Label

  lblİndirmeYüzdesi.Caption := IntToStr(Round((pbİndirmeGöstergesi.Position div pbİndirmeGöstergesi.Max) * 100));
end;

And I have also assigned Total File Size value to ProgressBar.Max value like this:

  btnDuraklat.Enabled := True;
  btnİndir.Enabled := False;

  strİndirilenDosya := 'OG9995-ARCTICO.rar';
  strLink := edİndirmeLinkiniGirmeKutusu.Text;

  indyDosyaİndirici := TIdHTTP.Create(nil);
  indyDosyaİndirici.OnWork := indyDosyaİndiriciWork;
  indyDosyaİndirici.OnWorkBegin := indyDosyaİndiriciWorkBegin;

  sslDosyaİndirici := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  sslDosyaİndirici.SSLOptions.Method := sslvTLSv1_2;

  indyDosyaİndirici.HandleRedirects := True;
  indyDosyaİndirici.IOHandler := sslDosyaİndirici;

  indyDosyaİndirici.Head(strLink);

  intSunucudakiDosyanınBoyutu := indyDosyaİndirici.Response.ContentLength;
  
  

intSunucudakiDosyanınBoyutu is Total File Size

  pbİndirmeGöstergesi.Max := intSunucudakiDosyanınBoyutu;

The progress bar works like a charm.

But the problem is that label does not show anything except 0 (zero).

How do I fix my problem?

1 Answers

You have to add the Update; method of the label, after you set the caption of the label. (eg: Label1.Update;)

Also you have to change the division from div (integer division) to / (floating-point division). For instance, 50 div 100 gives 0, but 50 / 100 gives 0.5

So, your code will change to this:

procedure TfrmDosyaİndirmeProgramı.indyDosyaİndiriciWork(ASender: TObject;
  AWorkMode: TWorkMode; AWorkCount: Int64);
begin
  pbİndirmeGöstergesi.Position := AWorkCount;
  lblİndirmeYüzdesi.Caption := IntToStr(Round((pbİndirmeGöstergesi.Position / pbİndirmeGöstergesi.Max) * 100));
  lblİndirmeYüzdesi.Update;
end;

A more clean code, would be something like this:

var
  Form1: TForm1;
  intTotalSize: Int64;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  strURL : String;
  strLocalFile : String;
  FS: TFileStream;
begin
  strURL := 'http://212.183.159.230/50MB.zip';
  strLocalFile := 'C:\50MB.zip';

  IdHTTP1.Head(strURL);
  ProgressBar1.Max := IdHTTP1.Response.ContentLength ;
  intTotalSize := IdHTTP1.Response.ContentLength;

  FS := TFileStream.Create(strLocalFile, fmCreate);
  IdHTTP1.Get(strURL, FS);

end;

procedure TForm1.IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  ProgressBar1.Position := AWorkCount;
  Label1.Caption := FormatFloat('0.##%', (AWorkCount / intTotalSize)*100);
  Label1.Update;
end;
Related