UrlLoader
Supported platforms: android, ios, mac, pc
Available since: Gideros 2012.2.2
Description
The `UrlLoader` class is used to download data from an URL. It can be used to download (and optionally save) text files, XML files, JSON files, image files or binary files, etc.
Downloaded data is delivered at `event.data` field of `Event.COMPLETE` event as string. Lua is eight-bit clean and so strings may contain characters with any numeric value, including embedded zeros. That means that you can store any binary data into a string.
HTTP Request Methods
UrlLoader supports GET, POST, PUT and DELETE methods. These are defined by these string constants:
- `UrlLoader.GET = "get"`
- `UrlLoader.POST = "post"`
- `UrlLoader.PUT = "put"`
- `UrlLoader.DELETE = "delete"`
Examples
The example below shows downloading an image file from an URL, saving it to the documents folder and displaying it
on the stage. This example also shows downloading progress and handling errors.
local loader = UrlLoader.new("http://example.com/image.png")<br />
<br />
local function onComplete(event)<br />
local out = io.open("|D|image.png", "wb")<br />
out:write(event.data)<br />
out:close()<br />
<br />
local b = Bitmap.new(Texture.new("|D|image.png"))<br />
stage:addChild(b)<br />
end<br />
<br />
local function onError()<br />
print("error")<br />
end<br />
<br />
local function onProgress(event)<br />
print("progress: " .. event.bytesLoaded .. " of " .. event.bytesTotal)<br />
end<br />
<br />
loader:addEventListener(Event.COMPLETE, onComplete)<br />
loader:addEventListener(Event.ERROR, onError)<br />
loader:addEventListener(Event.PROGRESS, onProgress)
Uploading a file
local filename = "crate.png"
local file = io.open(filename, "rb")
local contents = file:read( "*a" )
local boundary = "somerndstring"
local send = "--"..boundary..
"\r\nContent-Disposition: form-data; "..
"name="..filename.."; filename="..filename..
"\r\nContent-type: image/png"..
"\r\n\r\n"..contents..
"\r\n--"..boundary.."--\r\n";
local headers = {
["Content-Type"] = "multipart/form-data; boundary="..boundary,
["Content-Length"] = #send,
}
local loader = UrlLoader.new("http://localhost/gideros.php", UrlLoader.POST, headers, send)
loader:addEventListener(Event.COMPLETE, function(e)
print(e.data)
end)
MethodsUrlLoader.new - creates a new UrlLoader object |
EventsEvent.COMPLETE Constants |