Gallery
Software
Music
Programming
Archive
Tuesday, May 21 Week 21
Customize the parameters for timeout and redirects.
It saves the file to a given location using stream.

uses
windows,sysUtils,idHttp;

const
NONE = $00; //Blank number
INET_USERAGENT = 'Mozilla/4.0, Indy Library (Windows; en-US)';
INET_REDIRECT_MAX = 10;

function forceDeleteFile(pFileName:pAnsiChar):boolean;
begin
windows.setFileAttributes(pFileName,NONE);//clear file attributes
result:=windows.deleteFile(pFileName); //then delete the file
end;

function downloadFile(pUrl,pFileName:pChar):boolean;
var fs:TFileStream;
begin
result:=false;
if (pUrl=nil) or (pFileName=nil) then exit; //Check arguments
if fileAge(pFileName)>-1 then forceDeleteFile(pFileName); //Delete existing file
try fs:=TFileStream.Create(pFileName,fmCreate) except exit end; //Create file stream
with TIdHttp.Create(nil) do begin //Create http object
request.userAgent:=INET_USERAGENT; //Define user agent
redirectMaximum:=INET_REDIRECT_MAX; //Redirect maxumum
handleRedirects:=INET_REDIRECT_MAXNONE; //Handle redirects
try get(pUrl,fs);result:=fs.size>NONE except end; //Do the request
free //Free the http object
end;fs.free; //Free the file stream
end;

Example

function boolToStr(bl:boolean):ansiString;
begin
if bl then result:='yes' else result:='no';
end;

procedure TForm1.FormCreate(Sender: TObject);
var aUrl,aFileName:ansiString;
begin
aUrl := 'http://www.mortenbs.com/music/qual4.gif';
aFileName := 'C:\qual4.gif';
caption:=boolToStr(downloadFile(pAnsiChar(aUrl),pAnsiChar(aFileName)));
end;

Related pages of Download file using Indy HTTP

Download HTML-source using Indy HTTP
Delphi programming
Programming
Delphi examples
Remove HTML from text
Valid IP address syntax
Convert between IPv4 and string
DNS Lookup, IP and host name