Lianja
Lianja
Read Bytes from a Remote SFTP File (BinData)
See more SFTP Examples
Demonstrates the Chilkat SFtp.ReadFileBd method, which reads up to a number of bytes from the current position of an open handle and appends them to a BinData. The arguments are the handle, the maximum number of bytes, and the BinData. This example reads in chunks until end-of-file.
Background: For binary files, reading into a
BinData preserves the bytes exactly, unlike a text read that decodes through a charset. Because it appends, the chunked read loop accumulates the whole file in the BinData; each pass reads up to the chunk size and the loop repeats until Eof. Fewer bytes than requested can come back near the end of the file, which is normal.Chilkat Lianja Downloads
llSuccess = .F.
// Demonstrates the SFtp.ReadFileBd method, which reads up to a number of bytes from the current
// position of an open handle and appends them to a BinData. The 1st argument is the handle, the
// 2nd is the maximum number of bytes, and the 3rd 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
lcHandle = loSftp.OpenFile("subdir/image.png","readOnly","openExisting")
if (loSftp.LastMethodSuccess = .F.) then
? loSftp.LastErrorText
release loSftp
return
endif
// Read the file in chunks until end-of-file, accumulating the bytes in a BinData.
loBd = createobject("CkBinData")
lnChunkSize = 8192
llReading = .T.
do while llReading
llSuccess = loSftp.ReadFileBd(lcHandle,lnChunkSize,loBd)
if (loSftp.LastReadFailed(lcHandle)) then
? loSftp.LastErrorText
release loSftp
release loBd
return
endif
llReading = not loSftp.Eof(lcHandle)
enddo
llSuccess = loSftp.CloseHandle(lcHandle)
if (llSuccess = .F.) then
? loSftp.LastErrorText
release loSftp
release loBd
return
endif
? "Read " + str(loBd.NumBytes) + " bytes."
loSftp.Disconnect()
release loSftp
release loBd