How can I check if a file exists in a URL with IdHttp?

3

I need to check if a particular online file exists if it is True , if not False . Can anyone help?

    
asked by anonymous 17.04.2014 / 21:12

1 answer

2

This can be done through an HTTP request with the HEAD method to request information from a given resource, without it being returned.

According to Wikipedia :

  

GET variation where the resource is not returned. It is used to get meta-information through the response header, without having to retrieve all content.

Related: What are the HTTP request methods, and what is the difference between them?

See an example:

 
// Uses: IdHTTP, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient; 

function CheckFileOnlineExists(const OnlineFile: string; var Size: Int64): Boolean;
var
 IdHttp: TIdHTTP;
begin
try
  IdHttp := TIdHTTP.Create(nil);
  try
    IdHttp.Head(OnlineFile);
    Size := IdHttp.Response.ContentLength;
    if Size > 0 then
      Result := True
    else
      Result := False;
  except on E: EIdHTTPProtocolException do begin
    // Fazer algo aqui caso você queira tratar alguma exceção do IdHttp
  end;
  end;
finally
  IdHttp.Free;
end;
end;

The first parameter of the CheckFileOnlineExists function is the link of the file to be scanned, and the second parameter is an integer variable that will receive the content-length of the requisition (although it has not been requested in the matter).

Example usage:

 
Const
 LINK = 'http://cdn.sstatic.net/br/img/apple-touch-icon.png?v=3958fdf06794';
Var
 FileStatus: Boolean;
 FileSize: Int64;
begin
 FileStatus := CheckFileOnlineExists(LINK, FileSize);

 if FileStatus then
   ShowMessage(Format('Arquivo existente! Tamanho em bytes %d.', [FileSize]))
 else
   ShowMessage('Esse arquivo não existe!');
    
18.04.2014 / 07:01