在lua中通过url下载文件 [英] Download file by url in lua

查看:262
本文介绍了在lua中通过url下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Lua初学者在这里.:)

Lua beginner here. :)

我正在尝试通过url加载文件,但由于某种原因我太愚蠢了,无法在SO上获取所有代码示例以适合我使用.

I am trying to load a file by url and somehow I am just too stupid to get all the code samples here on SO to work for me.

从以下位置下载和存储文件给定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,
}

我的程序运行20到30秒,此后没有任何保存.创建了一个test.jpg,但是它是空的.我还尝试将 w+b 添加到 io.open() 第二个参数,但没有奏效.

my program runs for 20 - 30s and afterwards nothing is saved. There is a created test.jpg but it is empty. I also tried to add w+b to the io.open() second parameter but did not work.

推荐答案

以下作品:

-- 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()

您拥有的脚本也适用于我;如果无法访问该URL,则该文件可能为空(在这种情况下,我发布的脚本将返回错误).

The script you have works for me as well; the file may be empty if the URL can't be accessed (the script I posted will return an error in this case).

这篇关于在lua中通过url下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆