Downloading and creating files in a loop

local path = system.pathForFile( “hello.png”, system.DocumentsDirectory )
myFile = io.open( path, “w+b” )

– Request remote file and save data to local file
http.request{
url = “http://developer.anscamobile.com/demo/[filename].png”,
sink = ltn12.sink.file(myFile),
}

If I do the above in a loop condition, it will only EVER download and save the first file to the DocumentDirectory and all subsequent files will be created, but will be empty. According to my research, the http.request is synchronous, so this is very perplexing behavior.

Any help would be very appreciated, thanks =) [import]uid: 93100 topic_id: 22419 reply_id: 322419[/import]

And figured it out already… [import]uid: 93100 topic_id: 22419 reply_id: 89373[/import]

Posting how you did it for other users who might come across this in the future would be cool - if and only if you have time :wink:

Grats on figuring it out in < 15 mins, nicely done! [import]uid: 52491 topic_id: 22419 reply_id: 89389[/import]

25c says they all got downloaded as the same filename.

local path = system.pathForFile( "hello.png", system.DocumentsDirectory ) [import]uid: 108660 topic_id: 22419 reply_id: 89417[/import]

I was trying to re-use stuff… like the path and file handles. It was set to different filenames, yet re-using the path handle seemed to mess things up.

So instead… I figured, why not put it in its own little function with everything local and created each time.

function DownloadAndSaveFile(url, asset, puid)
local path = system.pathForFile(string.format("%s-%s", puid, asset), system.DocumentsDirectory)
local file = io.open(path, “w+b”)
url = string.format("%s%s", url, asset)
http.request{ url = url, sink = ltn12.sink.file(file) }
end

That seemed to of worked great and I have it all working on the device now.

Thanks for the responses =) [import]uid: 93100 topic_id: 22419 reply_id: 89475[/import]