network.download()

Type Function
Library network.*
Return value none
Revision Current Public Release (2014.2381)
Keywords asynchronous, http, https, get, post, download
See also network.request()
network.cancel()
network.upload()
networkRequest
display.loadRemoteImage()

Overview

This API is a convenience method that is very similar to the asynchronous network.request(), except that it always attempts to download the response to a local file that you specify. In fact, this method simply calls network.request(), putting the destination filename and baseDirectory parameters into params.response and specifying "download" progress notifications.

You can also use display.loadRemoteImage() to download and display a remote image in a single API call.

This function returns a handle that can be passed to network.cancel() in order to cancel the request.

Gotchas

You cannot execute a network download during an applicationSuspend or applicationExit event. After Corona suspends, no callbacks will fire. You can work around this by saving the request you wish to make to a file upon suspension. Then, on an applicationResume event, check if there is a pending download saved and, if so, execute it.

Android

On Android, you must add the following permission to the build.settings file.

settings =
{
   android =
   {
      usesPermissions =
      {
         "android.permission.INTERNET",
      },
   },
}

Syntax

network.download( url, method, listener [, params], filename [, baseDirectory] )
url (required)

String. The HTTP request URL. This must conform to the usual rules for URLs (see example below if you want to use non-ASCII characters in the URL).

method (required)

String. The HTTP method; acceptable values are "GET" (default) or "POST".

listener (required)

Listener. The listener function invoked at various phases of the HTTP operation. This is passed a networkRequest event.

This API provides "download" progress when progress is true, meaning that the listener will receive events for "began", "progress", and "ended" phases. If the progress parameter is not enabled, the listener will only be invoked with an "ended" phase.

params (optional)

Table. Table that specifies HTTP request or response processing options, including custom request headers or body.

  • params.headers — Table specifying request header values with string keys.
  • params.body — String containing the request body, if any.
  • params.timeout — Timeout in seconds. Default is 30 seconds.
  • params.bodyType — String indicating whether a string request body is "text" or "binary". Default is "text".
  • params.progress — Setting to true enables progress events. Default is nil, indicating that only the "ended" phase event is desired.
filename (required)

String. The name of the file to which the response will be saved.

baseDirectory (optional)

Constant. The directory where the file will be saved. Defaults to system.DocumentsDirectory if not provided. Cannot be set to system.ResourceDirectory since that directory is read-only.

Example

The following example downloads a remote image to a local file and displays it on screen:


local function networkListener( event )
    if ( event.isError ) then
        print( "Network error - download failed" )
    elseif ( event.phase == "began" ) then
        print( "Progress Phase: began" )
    elseif ( event.phase == "ended" ) then
        print( "Displaying response image file" )
        myImage = display.newImage( event.response.filename, event.response.baseDirectory, 60, 40 )
        myImage.alpha = 0
        transition.to( myImage, { alpha=1.0 } )
    end
end

local params = {}
params.progress = true

network.download(
    "http://docs.coronalabs.com/images/simulator/image-mask-base2.png",
    "GET",
    networkListener,
    params,
    "helloCopy.png",
    system.TemporaryDirectory
)

If you want to include non-ASCII characters in the URL you must urlencode them (your browser does this behind the scenes) as shown in this example:

local json = require "json"

function urlencode(str)
      if (str) then
          str = string.gsub (str, "\n", "\r\n")
          str = string.gsub (str, "([^%w ])",
              function ( c ) return string.format ("%%%02X", string.byte( c )) end)
          str = string.gsub (str, " ", "+")
      end
      return str
end

function myNetworkListener(event)
    print("myNetworkListener: "..json.encode(event, { indent = true } ))
end

addedText = "これはテストです"
local paramFormat = "&parm3=".. urlencode(addedText)
local request = "http://127.0.0.1/~tester/response.php?info=11&parm1=1&parm2=2".. paramFormat

network.download(request, "GET", myNetworkListener, "result.txt", system.DocumentsDirectory)