Article updated on

Download file from URL with Delphi or Lazarus

This example shows how to download a file using Delphi or Lazarus, the following features are covered.

  • Uses httpsend.
  • Gets HTTP return code in the response.
  • Create subfolders.

code

function DownloadHTTP(URL: string; FileName: string): boolean;
var
  httpClient: THTTPSend;
  noErrors: boolean = True;
  Path: string;
begin
  httpClient := THTTPSend.Create;
  trzvForm.escr(nDepuAlto, 'Va a descargar xml %s', [URL]);
  if httpClient.HTTPMethod('GET', URL) then
  begin
    // for windows
    FileName := StringReplace(FileName, '/', '\',
                          [rfReplaceAll, rfIgnoreCase]);
    // Gets the current path
    Path := IncludeTrailingPathDelimiter(GetCurrentDir) + FileName;
    // Creates folders if they don't exit
    if not DirectoryExists(ExtractFilePath(Path)) then
       begin
         ForceDirectories(ExtractFilePath(Path));
       end;
    // saves file
    httpClient.Document.SaveToFile(FileName);
    if httpClient.ResultCode = 200 then
      begin
        //it's been downloaded
      end
    else
      begin
        //httpClient.ResultCode is not 200
        noErrors := False;
        DeleteFile(ExtractFilePath(Path));
      end;
  end
  else
&nsp;   begin
      trzvForm.escr(nAlarma, 'Error while downloading %s', [URL]);
      noErrors := False;
    end;
  Result := noErrors;
  httpClient.Free;
end;