How to download a file in Lua, but write to a local file as it works

我们两清 提交于 2019-12-04 08:20:33

You are right - cURL can do it. LuaSocket does not have this functionality. You can create a LTN12 sink which will report progress made, but you won't know the total size of the file until you have downloaded it completely, so it is kind of useless. Why not use luacurl instead?

local curl = require "luacurl"
local c = curl.new()

function GET(url)
    c:setopt(curl.OPT_URL, url)
    local t = {} -- this will collect resulting chunks
    c:setopt(curl.OPT_WRITEFUNCTION, function (param, buf)
        table.insert(t, buf) -- store a chunk of data received
        return #buf
    end)
    c:setopt(curl.OPT_PROGRESSFUNCTION, function(param, dltotal, dlnow)
        print('%', url, dltotal, dlnow) -- do your fancy reporting here
    end)
    c:setopt(curl.OPT_NOPROGRESS, false) -- use this to activate progress
    assert(c:perform())
    return table.concat(t) -- return the whole data as a string
end

local s = GET 'http://www.lua.org/'
print(s)

You can save yourself the dependency on cURL by making a HEAD request and getting the filesize from the Content-Length header:

require "socket.http"

local resp, stat, hdr = socket.http.request{
  url     = "http://www.lua.org/ftp/lua-5.2.1.tar.gz",
  method  = "HEAD",
}

print(hdr["content-length"])
-- 249882

That said, if this is all you'd be using LuaSocket for, then cURL is arguably a better choice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!