Descargar un fichero desde una URL con Delphi

Para descargar un fichero mediante una URL, tenemos una librería llamada urlmon que nos puede servir para esto. El código ejemplo es el siguiente:



uses
Urlmon;

URLDownloadToFile(nil,PChar('http://www.prueba.com/images/files1.png'),PChar('C:\test.png'),0,nil);




de esta manera podemos descargarnos lo que queramos a nuestro ordenador, sin tener que utilizar un componente de browsing.

Otro ejemplo de descarga de contenido lo tenemos aquí, utilizando la librería WinInet:




function DownloadFile(const Url: string): string;
var
NetHandle: HINTERNET;
UrlHandle: HINTERNET;
Buffer: array[0..1024] of Char;
BytesRead: dWord;
begin
Result := '';
NetHandle := InternetOpen('Delphi 5.x', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);

if Assigned(NetHandle) then
begin
UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0);

if Assigned(UrlHandle) then
{ UrlHandle valid? Proceed with download }
begin
FillChar(Buffer, SizeOf(Buffer), 0);
repeat
Result := Result + Buffer;
FillChar(Buffer, SizeOf(Buffer), 0);
InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
until BytesRead = 0;
InternetCloseHandle(UrlHandle);
end
else
{ UrlHandle is not valid. Raise an exception. }
raise Exception.CreateFmt('Cannot open URL %s', [Url]);

InternetCloseHandle(NetHandle);
end
else
{ NetHandle is not valid. Raise an exception }
raise Exception.Create('Unable to initialize Wininet');
end;

memo1.lines.text := DownloadFile('http://www.prueba.com/index.html');




con este ejemplo, podemos descargarnos en contenido en texto dentro de un TMemo por ejemplo. Espero que os sirva de ayuda.

Comments

Popular Posts