Lua
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- 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.
local sftp = chilkat.SFtp.new()
-- Connect, authenticate, and initialize the SFTP subsystem.
local port = 22
local success = sftp:connect("sftp.example.com", port)
if not success then
print(sftp.last_error_text)
return
end
-- 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.
local password = "mySshPassword"
success = sftp:authenticate_pw("mySshLogin", password)
if not success then
print(sftp.last_error_text)
return
end
success = sftp:initialize_sftp()
if not success then
print(sftp.last_error_text)
return
end
local handle = sftp:open_file("subdir/image.png", "readOnly", "openExisting")
if not sftp.last_method_success then
print(sftp.last_error_text)
return
end
-- Read the file in chunks until end-of-file, accumulating the bytes in a BinData.
local bd = chilkat.BinData.new()
local chunkSize = 8192
local reading = true
while reading do
success = sftp:read_file_bd(handle, chunkSize, bd)
if sftp:last_read_failed(handle) then
print(sftp.last_error_text)
return
end
reading = not sftp:eof(handle)
end
success = sftp:close_handle(handle)
if not success then
print(sftp.last_error_text)
return
end
print("Read " .. bd.num_bytes .. " bytes.")
sftp:disconnect()