2015-04-15 74 views
1

Lua初學者在這裏。 :)通過lua中的url下載文件

我想加載一個文件的網址,不知何故,我太笨了,得到所有的代碼示例在這裏,爲我工作。

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

downloading and storing files from given url to given path in 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()第二個參數,但沒有奏效。

回答

4

以下工作:

-- 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,則該文件可能爲空(在本例中,我發佈的腳本將返回錯誤)。

+0

謝謝,我試過了,但我得到了暫停。 Test.lua:4:超時 棧回溯: \t [C]:在函數 '錯誤' \t ... I \下載\ ZeroBraneStudio \ myprograms \自治\ Test.lua:4:在主塊 \t [ C]:在0x00402a57 – sceiler

+0

這意味着某種連接問題,但不是Lua腳本的問題。嘗試從同一臺計算機上的瀏覽器訪問相同的URL,並且很可能會得到相同的錯誤。 –

+0

我試過但在瀏覽器(chrome)中打開它沒有問題。 – sceiler