Skip to main content

FTP download (ftp.download)

Declaration

done, info = ftp.download(URL, localPath [, connectTimeoutSec, resumeMode, onChunk, bufferSize ])

Parameters

  • URL
    String. Remote file URL. Username and password are included in this parameter.
  • localPath
    String. Local file path to save to.
  • connectTimeoutSec
    Number, optional. Connection timeout in seconds. Default: 10.
  • resumeMode
    Boolean, optional. Enable resume (breakpoint continuation) if true. Default: false.
  • onChunk
    Function, optional. Callback invoked after each chunk is transferred. Default: empty function.
    The first argument is the current transfer info. If the callback returns true, the download is aborted.
  • bufferSize
    Integer, optional. Buffer size in bytes. Default: auto-optimized.

Returns

  • done
    Boolean. Whether the connection/download succeeded.
  • info
    Table or String. If connection succeeded, returns a table with download info; otherwise a string describing the connection failure.

Notes

-- The structure of the second return value (info) is as follows
{
resource_size = total bytes of the remote resource,
start_pos = start position in the resource for this download,
size_download = bytes downloaded in this run,
speed_download = average speed in bytes/second,
}

Suitable for large file downloads; stopping the script during transfer may be slow.
This function may yield; other threads may run before it returns.

Simple example

Put credentials in the URL. Format (brackets denote optional parts):

ftp://[user:pass@]host[:port]/path

If username or password contains @, :, or /, use %40, %3A, %2F respectively. For other invalid URL characters, use URL-encode.
Example: user havonz, password 11@@22

local done, info = ftp.download("ftp://havonz:11%40%[email protected]/1.zip", "/var/mobile/1.zip")
if (done) then
sys.alert("If nothing unexpected happened, the file has been downloaded.")
else
sys.alert("Connection failed: "..info)
end

Advanced example

local done, info = ftp.download("ftp://havonz:[email protected]/1.zip", "/var/mobile/1.zip", 10, true, function(binfo)
local percent = math.floor(((binfo.start_pos + binfo.size_download) / binfo.resource_size) * 100)
sys.toast("Progress "..percent.."%")
end, 4096 * 1024)
--
if (done) then
if (info.start_pos + info.size_download < info.resource_size) then
sys.alert(
"Download interrupted\nThis run "..info.size_download.." bytes"
.."\nStarted at "..info.start_pos.." byte"
.."\nAverage speed "..math.floor(info.speed_download/1024).." kB/s"
.."\nRemaining "..(info.resource_size - (info.start_pos + info.size_download)).." bytes"
)
else
sys.alert(
"Download completed\nThis run "..info.size_download.." bytes"
.."\nStarted at "..info.start_pos.." byte"
.."\nAverage speed "..math.floor(info.speed_download/1024).." kB/s"
)
end
else
sys.alert("Connection failed: "..info)
end

Note: Uses sys.alert, sys.toast