Article updated on

Descargar un archivo desde una URL con Delphi o Lazarus

En este ejemplo se muestra como descargar un fichero desde Delphi o Lazarus .

  • Se usa httpsend.
  • Se captura el código de retorno del servidor tras hacer la petición.
  • Crea los directorios del ficheros si se especifica

Código

//Funcion que descargar un Fichero dada una URL devuelve true cuando se
//baja OK el fichero
function DownloadHTTP(URL: string; FileName: string): boolean;
var
  httpClient: THTTPSend;
  sinErrores: boolean = True;
  Path: string;
begin
  httpClient := THTTPSend.Create;
  trzvForm.escr(nDepuAlto, 'Va a descargar xml %s', [URL]);
  if httpClient.HTTPMethod('GET', URL) then
  begin
    // para windows
    FileName := StringReplace(FileName, '/', '\',
                          [rfReplaceAll, rfIgnoreCase]);
    // Obtiene la ruta absoluta actual
    Path := IncludeTrailingPathDelimiter(GetCurrentDir) + FileName;
    // Crea el directorio si no existe
    if not DirectoryExists(ExtractFilePath(Path)) then
       begin
         //crea los directorios
         ForceDirectories(ExtractFilePath(Path));
       end;
    // Guarda el archivo
    httpClient.Document.SaveToFile(FileName);
    if httpClient.ResultCode = 200 then
      begin
        //descargado OK
      end
    else
      begin
        //httpClient.ResultCode no es 200
        sinErrores := False;
        DeleteFile(ExtractFilePath(Path));
      end;
  end
  else
&nsp;   begin
      trzvForm.escr(nAlarma, 'Falla al descargar %s', [URL]);
      sinErrores := False;
    end;
  Result := sinErrores;
  httpClient.Free;
end;