Forum > Networking and Web Programming

File Downloading

(1/1)

Lazerus:
Hi, everyone!

How can I donwload file from server using Lazarus?

typo:
ShellExecute(handle, 'open', PChar(DownloadableFileString), '','', SW_SHOWNORMAL); 

uses Windows.

Ocye:

--- Quote ---uses Windows
--- End quote ---
Pfui, use Synapse!


--- Code: ---uses ...HTTPSend, blcksock;
type
  THttpFile=class(THttpSend)
    private
    public
      function Download(const aURL,aFileName:string):boolean;
    end;

function THttpFile.Download(const aURL,aFileName: string): boolean;
begin
  HTTPMethod('GET', aURL+aFileName);
  with TFileStream.Create(aFileName,fmCreate or fmOpenWrite) do
  try
    Seek(0, soFromBeginning);
    CopyFrom(Document, 0);
  finally
    Free;
  end;
end;

--- End code ---

Take care of resultcode from HttMethod().

fabienwang:
Oh thanks Ocye i was exactly searching for the same.

Careful the latest Synapse methods changed, you will have to use HttpGetBinary

mvaldez:
With Indy 10, in Linux and Windows (and Mac?), I'd use something like:


--- Code: ---uses IdHTTP, IdAntiFreeze;

FUNCTION Download_File (FileURL, FileFileName : STRING) : BOOLEAN;
VAR
  HTTPClient: TIdHTTP;
  Antifreeze : TIdAntiFreeze;
  FileStream : TMemoryStream;
BEGIN
  Download_File := FALSE;
    HTTPClient := TIdHTTP.Create (NIL);
    HTTPClient.HandleRedirects := TRUE;
    // If we are behind a proxy...
    //HTTPClient.ProxyParams.ProxyServer := '192.168.246.254';
    //HTTPClient.ProxyParams.ProxyPort := 800;
    Antifreeze := TIdAntiFreeze.Create (NIL);
    // If parameters are empty, do nothing...
    IF ((FileURL <> '') AND (FileFileName <> '')) THEN
      BEGIN
        // Remove target local file...
        SysUtils.DELETEFILE (FileFileName);
        // Encode URL...
        FileURL := HTTPClient.URL.URLEncode (FileURL);
        HTTPClient.Disconnect;
        FileStream := TMemoryStream.Create;
        TRY
          // Download the file...
          HTTPClient.Get (FileURL, FileStream);
          // Save the file...
          FileStream.SaveToFile (FileFileName);
          Download_File := TRUE;
        EXCEPT
        END;
        FileStream.Free;
      END;
    Antifreeze.Free;
    HTTPClient.Free;
END;

--- End code ---

The .lpr (if using Linux) would need the unit cthreads as first unit, or you'll get a Runtime error.

And you may want to use TRY... FINALLY... blocks between every .Create and .Free procedures.


Regards,

MV

Navigation

[0] Message Index

Go to full version