Download file by url in lua

sceiler picture sceiler · Apr 15, 2015 · Viewed 9k times · Source

Lua beginner here. :)

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.

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,
}

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.

Answer

Paul Kulchenko picture Paul Kulchenko · Apr 15, 2015

The following works:

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

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