Skip to main content

Download file over HTTP (http.download)

Declaration

done, info = http.download(URL, local_path [, connect_timeout_secs, resume, on_chunk, buffer_size ])

Parameters

  • URL
    String. Remote file URL.
  • local_path
    String. Local file path to save.
  • connect_timeout_secs
    Number, optional. Connection timeout in seconds. Default 10.
  • resume
    Boolean, optional. Enable resume. Default false.
  • on_chunk
    Function, optional. Called for each chunk; receives current info and returns true to abort.
  • buffer_size
    Integer, optional. Buffer size in bytes. Default auto.

Returns

  • done
    Boolean. Whether connection and download succeeded.
  • info
    Table or String. Info table on success, otherwise error message string.

Notes

-- Structure of the info table
{
resource_size = total remote bytes,
start_pos = start position of this download,
size_download = bytes downloaded this time,
speed_download = average speed (bytes/sec),
}

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

Simple example

local done, info = http.download("https://192.168.31.13/1.zip", "/var/mobile/1.zip")
if (done) then
sys.alert("Downloaded successfully if no errors occurred")
else
sys.alert("Connection failed: "..info)
end

Advanced example

local done, info = http.download("https://192.168.31.13/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\nDownloaded "..info.size_download.." bytes"
.."\nStarted at "..info.start_pos
.."\nAvg speed "..math.floor(info.speed_download/1024).." kB/s"
.."\nRemaining "..(info.resource_size - (info.start_pos + info.size_download)).." bytes"
)
else
sys.alert(
"Download complete\nDownloaded "..info.size_download.." bytes"
.."\nStarted at "..info.start_pos
.."\nAvg speed "..math.floor(info.speed_download/1024).." kB/s"
)
end
else
sys.alert("Connection failed: "..info)
end

Note: Uses sys.alert, sys.toast

Error reference

  • Requested range was not delivered by the server: the server may not support resume; set resume to false.