How can I check if there is a file in an URL with Idhttp?

Asked

Viewed 2,003 times

3

I need to check if a particular file online is existing if it will return True, if not, False. Anyone can help?

  • I would advise you to exchange Indy for Ipworks, if you have conditions, of course. I used Indy for a long time, but there was a lot of bug and eventually I switched, I’m not remembering how you did it you want. If you come to change let me know, for then I will know the answer.

  • Where do I find this Ipworks component friend ?

  • That’s the problem, it’s paid for, but you can download the trial version here: http://www.nsoftware.com/ipworks/ But if I’m not mistaken it already comes installed with some of the newer versions of Delphi, like the XE2, XE3, pebble. Look for IP*Workws! in your Tool Palette, maybe you already have it and do not know. What is your version of Delphi?

  • OK I’ll test, thanks buddy..

1 answer

3

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

According to the Wikipedia:

Variation of GET where the resource is not returned. It is used to get meta-information through the response header without having to recover all the content.

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

Take 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 function parameter CheckFileOnlineExists is the file link to be checked, and the second parameter is a variable of type whole that will receive the content-length of the request (although it was not requested in the question).

Example of use:

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!');
  • Thanks for the tip,!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.