在lua中通过url下载文件

sce*_*ler 1 lua luasocket

Lua初学者在这里.:)

我正在尝试通过url加载文件,不知何故,我太愚蠢了,无法在此处获取所有代码示例,以便为我工作.

如何在Lua中下载文件,但在工作时写入本地文件

从给定的URL下载和存储文件到lua中的给定路径

socket = require("socket")
http = require("socket.http")
ltn12 = require("ltn12")

local file = ltn12.sink.file(io.open('test.jpg', 'w'))
http.request {
    url = 'http://pbs.twimg.com/media/CCROQ8vUEAEgFke.jpg',
    sink = file,
}
Run Code Online (Sandbox Code Playgroud)

我的程序运行20 - 30s,之后没有保存.有一个创建的test.jpg但它是空的.我也尝试将w + b添加到io.open()第二个参数但是没有用.

Pau*_*nko 6

以下作品:

-- retrieve the content of a URL
local http = require("socket.http")
local body, code = http.request("http://pbs.twimg.com/media/CCROQ8vUEAEgFke.jpg")
if not body then error(code) end

-- save the content to a file
local f = assert(io.open('test.jpg', 'wb')) -- open in "binary" mode
f:write(body)
f:close()
Run Code Online (Sandbox Code Playgroud)

你的剧本也适合我; 如果无法访问URL,则该文件可能为空(在此情况下,我发布的脚本将返回错误).