Sample code for 30+ languages & platforms
PureBasic

Download an FTP File to a Stream

See more FTP Examples

Demonstrates the Chilkat Ftp2.GetFileToStream method, which downloads a remote file and writes its bytes to a Stream. The first argument is the remote file path and the second is the Stream, which must have a destination sink configured beforehand.

Note: The local paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: Streaming to a Stream object decouples the download from where the bytes ultimately go — a file (as here, via SinkFile), or a pipe feeding another component such as a decompressor or a hashing routine — and processes the data as it arrives rather than buffering the whole file. That keeps memory flat for large downloads and lets you chain the transfer into a processing pipeline.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkFtp2.pb"
IncludeFile "CkStream.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Demonstrates the Ftp2.GetFileToStream method, which downloads a remote file and writes its
    ;  bytes to a Stream.  The 1st argument is the remote file path and the 2nd is the Stream.

    ftp.i = CkFtp2::ckCreate()
    If ftp.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkFtp2::setCkHostname(ftp, "ftp.example.com")
    CkFtp2::setCkUsername(ftp, "myFtpLogin")

    ;  Normally you would not hard-code the password in source.  You should instead obtain it
    ;  from an interactive prompt, environment variable, or a secrets vault.
    CkFtp2::setCkPassword(ftp, "myPassword")

    success = CkFtp2::ckConnect(ftp)
    If success = 0
        Debug CkFtp2::ckLastErrorText(ftp)
        CkFtp2::ckDispose(ftp)
        ProcedureReturn
    EndIf

    ;  Configure the stream's destination sink before downloading.  Here the stream writes to a
    ;  local file.
    fileStream.i = CkStream::ckCreate()
    If fileStream.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStream::setCkSinkFile(fileStream, "qa_output/report.pdf")

    success = CkFtp2::ckGetFileToStream(ftp,"public_html/report.pdf",fileStream)
    If success = 0
        Debug CkFtp2::ckLastErrorText(ftp)
        CkFtp2::ckDispose(ftp)
        CkStream::ckDispose(fileStream)
        ProcedureReturn
    EndIf

    Debug "Downloaded to stream."

    success = CkFtp2::ckDisconnect(ftp)
    If success = 0
        Debug CkFtp2::ckLastErrorText(ftp)
        CkFtp2::ckDispose(ftp)
        CkStream::ckDispose(fileStream)
        ProcedureReturn
    EndIf



    CkFtp2::ckDispose(ftp)
    CkStream::ckDispose(fileStream)


    ProcedureReturn
EndProcedure