Sample code for 30+ languages & platforms
Lianja

Write Bytes to a Remote SFTP File (BinData)

See more SFTP Examples

Demonstrates the Chilkat SFtp.WriteFileBd method, which appends all bytes in a BinData to the remote file identified by an open handle. The first argument is the handle and the second is the BinData.

Note: This example uses a relative local path, which is resolved against the application's current working directory. Absolute local paths may also be used. Supply the path appropriate to your own environment.

Background: This is the binary counterpart to WriteFileText — the right choice for images, archives, or any non-text content, where a charset conversion would corrupt the data. Combined with an appropriate OpenFile disposition it can create, overwrite, or append; here the file is created/truncated first so the result is exactly the BinData contents.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

//  Demonstrates the SFtp.WriteFileBd method, which appends all bytes in a BinData to the remote
//  file identified by an open handle.  The 1st argument is the handle and the 2nd is the BinData.

loSftp = createobject("CkSFtp")

//  Connect, authenticate, and initialize the SFTP subsystem.
lnPort = 22
llSuccess = loSftp.Connect("sftp.example.com",lnPort)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

//  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.
lcPassword = "mySshPassword"

llSuccess = loSftp.AuthenticatePw("mySshLogin",lcPassword)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

llSuccess = loSftp.InitializeSftp()
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

//  Open (creating/truncating) the remote file for writing.
lcHandle = loSftp.OpenFile("subdir/image.png","writeOnly","createTruncate")
if (loSftp.LastMethodSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

//  Put the bytes to write into a BinData.  (Here they are loaded from a local file, but the
//  bytes could come from anywhere.)
loBd = createobject("CkBinData")
llSuccess = loBd.LoadFile("qa_data/image.png")
if (llSuccess = .F.) then
    ? loBd.LastErrorText
    release loSftp
    release loBd
    return
endif

//  Append the BinData bytes to the open remote file.
llSuccess = loSftp.WriteFileBd(lcHandle,loBd)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    release loBd
    return
endif

llSuccess = loSftp.CloseHandle(lcHandle)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    release loBd
    return
endif

? "Wrote " + str(loBd.NumBytes) + " bytes."

loSftp.Disconnect()


release loSftp
release loBd