Fórum [Dúvida] Download + ProgressBar #623760

12/06/2025

0

Boa tarde galera, estou tentando fazer uma aplicação em delphi12, para baixar um arquivo da net, e que mostra o progress pela progressbar, mas está dando esse error e nao estou conseguindo resolver

[dcc32 Error] Launcher.pas(133): E2010 Incompatible types: ''Int64'' and ''Integer''


Segue me codigo:

procedure TForm1.UpdateProgress(Sender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer);
begin
  if AWorkMode = wmRead then
  begin
    // Converter AWorkCount (Integer) para Int64 e atualizar FDownloaded
    FDownloaded := FDownloaded + Int64(AWorkCount);

    // Atualiza a ProgressBar com os valores Int64
    ProgressBar1.Max := FFileSize;
    ProgressBar1.Position := Integer(FDownloaded);  // A ProgressBar requer Integer

    // Atualiza a Label com a porcentagem de progresso
    if FFileSize > 0 then
      Label1.Caption := Format(''Baixando... %.2f%%'', [FDownloaded * 100 / FFileSize])
    else
      Label1.Caption := ''Baixando...'';
  end;
end;

procedure TForm1.DownloadFile(const URL, Destino: string);
var
  HTTP: TIdHTTP;
  FileStream: TFileStream;
begin
  HTTP := TIdHTTP.Create(nil);
  FileStream := TFileStream.Create(Destino, fmCreate); // Cria o arquivo no destino
  try
    // Obtém o tamanho do arquivo (para calcular o progresso)
    HTTP.Head(URL);
    FFileSize := HTTP.Response.ContentLength;  // Atribui o tamanho do arquivo ao campo FFileSize
    FDownloaded := 0; // Inicializa os bytes baixados

    // Configura a ProgressBar
    ProgressBar1.Max := FFileSize;
    ProgressBar1.Position := 0;  // Reseta a ProgressBar
    Label1.Caption := ''Baixando... 0%'';  // Exibe 0% inicialmente

    // Associa o evento OnWork ao método UpdateProgress
    HTTP.OnWork := UpdateProgress;

    // Inicia o download
    HTTP.Get(URL, FileStream); // Baixa o arquivo para o FileStream
  finally
    HTTP.Free;
    FileStream.Free; // Libera o FileStream
  end;
end;
Wallace

Wallace

Responder

Post mais votado

13/06/2025

Fala Wallace,

* *Está acontecendo provavelmente nesta linha:*
** ProgressBar1.Position := Integer(FDownloaded);

* * Solução segura*
** Verifique se FDownloaded está dentro do limite antes de converter:

* *Exemplo: *
if FDownloaded <= MaxInt then
ProgressBar1.Position := FDownloaded
else
ProgressBar1.Position := MaxInt; // limita o progresso ao máximo da barra

A seguir segue um exemplo funcional:
unit Unit1;

interface

uses
  SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, 
  QDialogs, QStdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdHTTP, QComCtrls;

type
  TForm1 = class(TForm)
    btnDownload: TButton;
    ProgressBar1: TProgressBar;
    Label1: TLabel;
    IdHTTP1: TIdHTTP;
    memoLog: TMemo;
    procedure UpdateProgressWork(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer);
    procedure btnDownloadClick(Sender: TObject);
    procedure IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
      const AWorkCount: Integer);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    FDownloaded: Int64;
    FFileSize: Int64;
    procedure AddLog(const AMessage: string);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.xfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  memoLog.Clear;
  AddLog('Aplicativo iniciado.');
end;

procedure TForm1.AddLog(const AMessage: string);
begin
  memoLog.Lines.Add(FormatDateTime('[dd/mm/yyyy hh:nn:ss] ', Now) + AMessage);

  memoLog.SelStart := Length(memoLog.Text);
  memoLog.SelLength := 0;

  memoLog.SetFocus;
end;

procedure TForm1.UpdateProgressWork(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer);
var
  ProgressPercent: Double;
  LastProgress: Integer;
begin
  if AWorkMode = wmRead then
  begin
    FDownloaded := FDownloaded + AWorkCount;
    
    // Limitar o progresso para evitar que ultrapasse 100%
    if FDownloaded > FFileSize then
      FDownloaded := FFileSize;

    if FFileSize <= MaxInt then
    begin
      if FDownloaded <= MaxInt then
        ProgressBar1.Position := FDownloaded
      else
        ProgressBar1.Position := MaxInt;
    end;

    if FFileSize > 0 then
    begin
      ProgressPercent := (FDownloaded * 100.0) / FFileSize;
      if ProgressPercent > 100 then ProgressPercent := 100;
      
      Label1.Caption := Format('Baixando... %.2f%%', [ProgressPercent]);
      
      // Adicionar log a cada 10% do progresso (usando variável estática)
      LastProgress := Trunc(ProgressPercent);
      if (LastProgress mod 10 = 0) and (LastProgress > 0) and (LastProgress <= 100) then
      begin
        // Usar Tag para guardar o último valor de progresso registrado
        if LastProgress <> ProgressBar1.Tag then
        begin
          ProgressBar1.Tag := LastProgress;
          AddLog(Format('Progresso: %.2f%% (%d de %d bytes)', 
                 [ProgressPercent, FDownloaded, FFileSize]));
        end;
      end;
    end
    else
      Label1.Caption := 'Baixando...';
  end;
end;


procedure TForm1.btnDownloadClick(Sender: TObject);
var
  FileStream: TFileStream;
  URL, Destino: string;
begin
  memoLog.Clear;
  
  // URL HTTP em vez de HTTPS
  URL := 'http://speedtest.tele2.net/10MB.zip'; 
  Destino := ExtractFilePath(Application.ExeName) + 'download_test.zip';

  AddLog('Iniciando download de: ' + URL);
  AddLog('Destino: ' + Destino);

  IdHTTP1.OnWork := UpdateProgressWork;
  ProgressBar1.Tag := -1; // Reseta o valor do último progresso

  FileStream := TFileStream.Create(Destino, fmCreate);
  try
    try
      AddLog('Verificando tamanho do arquivo...');
      IdHTTP1.Head(URL);
      FFileSize := IdHTTP1.Response.ContentLength;
      AddLog(Format('Tamanho do arquivo: %d bytes (%.2f MB)', 
             [FFileSize, FFileSize / 1024 / 1024]));
      
      FDownloaded := 0;

      if FFileSize <= MaxInt then
        ProgressBar1.Max := FFileSize
      else
        ProgressBar1.Max := MaxInt;

      ProgressBar1.Position := 0;
      Label1.Caption := 'Baixando... 0%';
      
      AddLog('Iniciando download do arquivo...');
      IdHTTP1.Get(URL, FileStream);
      AddLog('Download concluído com sucesso!');
      ShowMessage('Download concluído com sucesso!');
    except
      on E: Exception do
      begin
        AddLog('ERRO: ' + E.Message);
        ShowMessage('Erro durante o download: ' + E.Message);
      end;
    end;
  finally
    FileStream.Free;
  end;
end;

procedure TForm1.IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCount: Integer);
begin
    // Exemplo de uso
end;

end.




Boa tarde Raimundo, Raimundo.

Poderia dispor da source deste projeto que você enviou, porque ainda continuo com o mesmo problema,.

Wallace

Wallace
Responder

Gostei + 1

Mais Posts

13/06/2025

Raimundo Pereira

Fala Wallace,

* *Está acontecendo provavelmente nesta linha:*
** ProgressBar1.Position := Integer(FDownloaded);

* * Solução segura*
** Verifique se FDownloaded está dentro do limite antes de converter:

* *Exemplo: *
if FDownloaded <= MaxInt then
ProgressBar1.Position := FDownloaded
else
ProgressBar1.Position := MaxInt; // limita o progresso ao máximo da barra

A seguir segue um exemplo funcional:
unit Unit1;

interface

uses
  SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, 
  QDialogs, QStdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdHTTP, QComCtrls;

type
  TForm1 = class(TForm)
    btnDownload: TButton;
    ProgressBar1: TProgressBar;
    Label1: TLabel;
    IdHTTP1: TIdHTTP;
    memoLog: TMemo;
    procedure UpdateProgressWork(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer);
    procedure btnDownloadClick(Sender: TObject);
    procedure IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
      const AWorkCount: Integer);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    FDownloaded: Int64;
    FFileSize: Int64;
    procedure AddLog(const AMessage: string);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.xfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  memoLog.Clear;
  AddLog('Aplicativo iniciado.');
end;

procedure TForm1.AddLog(const AMessage: string);
begin
  memoLog.Lines.Add(FormatDateTime('[dd/mm/yyyy hh:nn:ss] ', Now) + AMessage);

  memoLog.SelStart := Length(memoLog.Text);
  memoLog.SelLength := 0;

  memoLog.SetFocus;
end;

procedure TForm1.UpdateProgressWork(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer);
var
  ProgressPercent: Double;
  LastProgress: Integer;
begin
  if AWorkMode = wmRead then
  begin
    FDownloaded := FDownloaded + AWorkCount;
    
    // Limitar o progresso para evitar que ultrapasse 100%
    if FDownloaded > FFileSize then
      FDownloaded := FFileSize;

    if FFileSize <= MaxInt then
    begin
      if FDownloaded <= MaxInt then
        ProgressBar1.Position := FDownloaded
      else
        ProgressBar1.Position := MaxInt;
    end;

    if FFileSize > 0 then
    begin
      ProgressPercent := (FDownloaded * 100.0) / FFileSize;
      if ProgressPercent > 100 then ProgressPercent := 100;
      
      Label1.Caption := Format('Baixando... %.2f%%', [ProgressPercent]);
      
      // Adicionar log a cada 10% do progresso (usando variável estática)
      LastProgress := Trunc(ProgressPercent);
      if (LastProgress mod 10 = 0) and (LastProgress > 0) and (LastProgress <= 100) then
      begin
        // Usar Tag para guardar o último valor de progresso registrado
        if LastProgress <> ProgressBar1.Tag then
        begin
          ProgressBar1.Tag := LastProgress;
          AddLog(Format('Progresso: %.2f%% (%d de %d bytes)', 
                 [ProgressPercent, FDownloaded, FFileSize]));
        end;
      end;
    end
    else
      Label1.Caption := 'Baixando...';
  end;
end;


procedure TForm1.btnDownloadClick(Sender: TObject);
var
  FileStream: TFileStream;
  URL, Destino: string;
begin
  memoLog.Clear;
  
  // URL HTTP em vez de HTTPS
  URL := 'http://speedtest.tele2.net/10MB.zip'; 
  Destino := ExtractFilePath(Application.ExeName) + 'download_test.zip';

  AddLog('Iniciando download de: ' + URL);
  AddLog('Destino: ' + Destino);

  IdHTTP1.OnWork := UpdateProgressWork;
  ProgressBar1.Tag := -1; // Reseta o valor do último progresso

  FileStream := TFileStream.Create(Destino, fmCreate);
  try
    try
      AddLog('Verificando tamanho do arquivo...');
      IdHTTP1.Head(URL);
      FFileSize := IdHTTP1.Response.ContentLength;
      AddLog(Format('Tamanho do arquivo: %d bytes (%.2f MB)', 
             [FFileSize, FFileSize / 1024 / 1024]));
      
      FDownloaded := 0;

      if FFileSize <= MaxInt then
        ProgressBar1.Max := FFileSize
      else
        ProgressBar1.Max := MaxInt;

      ProgressBar1.Position := 0;
      Label1.Caption := 'Baixando... 0%';
      
      AddLog('Iniciando download do arquivo...');
      IdHTTP1.Get(URL, FileStream);
      AddLog('Download concluído com sucesso!');
      ShowMessage('Download concluído com sucesso!');
    except
      on E: Exception do
      begin
        AddLog('ERRO: ' + E.Message);
        ShowMessage('Erro durante o download: ' + E.Message);
      end;
    end;
  finally
    FileStream.Free;
  end;
end;

procedure TForm1.IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCount: Integer);
begin
    // Exemplo de uso
end;

end.


Responder

Gostei + 0

13/06/2025

Raimundo Pereira

Segue link para download
https://drive.google.com/file/d/1LgZI_o573GaqnppS8wE0ZuX4ydvFhEN7/view?usp=drive_link
Responder

Gostei + 0

13/06/2025

Wallace

Segue link para download
https://drive.google.com/file/d/1LgZI_o573GaqnppS8wE0ZuX4ydvFhEN7/view?usp=drive_link


está dando esse error ao entrar no link

"Não é possível acessar este item porque ele viola nossos Termos de Serviço.

Saiba mais sobre este tema na Central de Ajuda do Google Drive."
Responder

Gostei + 0

13/06/2025

Arthur Heinrich

A função do progress bar é mostrar um progresso de 0 a 100%, baseado no valor máximo (max) e a posição atual (position). Ambos os parâmetros são do tipo Integer, que vai até 2^31-1, cerca de 2 bilhões.

Já os arquivos, podem tem mais de 2 GB e, por isso, se utiliza o tipo Int64, de 64 bits.

Quando você atribui um valor às propriedades Max e position, tem que ser dentro dos limites do Integer.

Você pode fazer o seguinte:

    ProgressBar1.Max := 100;
    ProgressBar1.Position := Round(100*FDownloaded/FFileSize);

Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar