Loading files using the URLLoader and URLVariables classes

Not sure if this is helpful to anybody, but thought I’d throw it out there. The following basic example loads some random variables from an external text file and displays the events which were dispatched in a DataGrid control, as well as the loaded name/value pairs.

Full code after the jump.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" verticalAlign="middle" backgroundColor="white" creationComplete="init()">

            import mx.collections.ArrayCollection;

            private var VARIABLES_URL:String = "params.txt";

            private var arrColl:ArrayCollection;

            private var paramColl:ArrayCollection;

            private var urlReq:URLRequest;
            private var urlLdr:URLLoader;

            private function init():void {
                /* Initialize the two ArrayCollections objects with empty arrays. */
                arrColl = new ArrayCollection();
                paramColl = new ArrayCollection();

                /* Initialize the URLRequest object with the URL to the file of name/value pairs. */
                urlReq = new URLRequest(VARIABLES_URL);

                /* Initialize the URLLoader object, assign the various event listeners, and load the specified URLRequest object. */
                urlLdr = new URLLoader();
                urlLdr.addEventListener(Event.COMPLETE, doEvent);
                urlLdr.addEventListener(Event.OPEN, doEvent);
                urlLdr.addEventListener(HTTPStatusEvent.HTTP_STATUS, doEvent);
                urlLdr.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
                urlLdr.addEventListener(ProgressEvent.PROGRESS, doEvent);
                urlLdr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);

            private function doEvent(evt:Event):void {
                arrColl.addItem({type:evt.type, idx:arrColl.length+1, eventString:evt.toString()});

                switch (evt.type) {
                    case Event.COMPLETE:
                        /* If the load was successful, create a URLVariables object from the URLLoader.data property and populate the paramColl ArrayCollection object. */
                        var ldr:URLLoader = evt.currentTarget as URLLoader;
                        var vars:URLVariables = new URLVariables(ldr.data);
                        var key:String;

                        for (key in vars) {
                            paramColl.addItem({key:key, value:vars[key]});

                        params.visible = true;

        <mx:Label text="Events:" />
        <mx:DataGrid id="events" dataProvider="{arrColl}" rowCount="5">
                <mx:DataGridColumn dataField="idx" headerText="#" width="20" />
                <mx:DataGridColumn dataField="type" headerText="Type" showDataTips="true" dataTipField="eventString" />

        <mx:Label text="Parameters:" />
        <mx:DataGrid id="params" dataProvider="{paramColl}" rowCount="5" visible="false">
                <mx:DataGridColumn dataField="key" headerText="Key" />
                <mx:DataGridColumn dataField="value" headerText="Value" />


15 thoughts on “Loading files using the URLLoader and URLVariables classes

  1. This was helpful to me. I’m porting a small Java Swing based application to Flex which stored individual user information in .properties files (One for each user.) I’ve been looking for several days for informationhow to load and read text based properties in Flex. Thanks for posting

  2. I’ve been searching for solution on unload the data loaded using URLLoader by clicking a checkbox. Any help will be appreciated. Thanks.

  3. HI,
    I tried this code with following content in txt file:-

    age= 28
    name= Dharmendra

    It always reads first key value pair.ie it does not load secont key value pair.
    Do we need any kind of saperator in order to read all key value pair properly.


  4. Hi Dharmendra,
    I have some requirement like you have. Please let me know, if you find any solution.

  5. Hi Dharmendra:

    from the Flex docs, it seems that the URLVariables class is meant to be used for passing url parameters when constructing a request going from the client to the server (in here is being used for parsing properties which is slightly different). What I’ve found is that the URLVariables class tokenizes the variables using the & as a delimiter, so:

    var vars:URLVariables = new URLVariables(“a=foo&b=baz&c=bar”);

    will be correctly split as name-value pairs. This is the reason why you only see the first name-value pair from your properties file, as this file uses a new line character as the tokenizer.

    I got the example provided above to work by replacing the code:

    var vars:URLVariables = new URLVariables(ldr.data);
    var key:String;

    for (key in vars) {
    paramColl.addItem({key:key, value:vars[key]});


    var lines:Array = ( ldr.data as String ).split( “\n” );

    for each ( var line:String in lines ) {
    var pair:Array = line.split( “=” );
    paramColl.addItem( { key:pair[0], value:pair[1] } );

    Thank you very much to Peter for sharing the snippet.

  6. I am having problems with this URLLoader. When I run the app, I initialize a URLLoader object to get my XML. The first I get my data it’s find. I go to update the data, the data is sent from Flex to a webservice. The webservice saves the data. Trust. I checked. It did overwrite the file and save properly. Flex received word that the webservice call was successfully, so go to load that same xml file again. It loads, but it loads the previous stuff, not exactly the new file. What am I doing wrong?

  7. hi frnds,
    I m using URLVariables / url loader properties for exporting csv results..

    but i m getting this error,
    can anyone pls solve this problem?
    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
    at Error$/throwError()
    at flash.net::URLVariables/decode()
    at flash.net::URLVariables()

    1. Your probably using this line of code:

      loader.dataFormat = URLLoaderDataFormat.VARIABLES;


      I don’t know what the deal is, but it seems there is a mistake with the URLLoaderDataFormat, change your type to URLLoaderDataFormat.TEXT or URLLoaderDataFormat.BINARY or make the line say this instead:

      loader.dataFormat = “VARIABLES”;
      and it should work. The URLLoaderDataFormat.VARIABLES is “variables” instead of “VARIABLES”.

  8. hi,
    I’m not sure if this is the right place to ask my question, but here goes.

    I need a simple array with filenames that are inside a given directory.
    so, I have a function getallfilesinfolder(foldername:string):array
    var arr:Array = new Array();

    return arr;

    lets say i have a folder called http://www.mywebsite.com/images/cars/

    inside that cars folder are an x number of images (jpg, png)

    in air i use this:
    public function getallfilesinfolder(foldername:String):Array
    var filearray:Array=new Array();
    var directory:File = File.applicationDirectory;
    directory = directory.resolvePath(“gardenimages/”+foldername+””);
    var contents:Array = directory.getDirectoryListing();
    for (var i:Number = 0; i < contents.length; i++)
    if(contents[i].type==".jpg" ||contents[i].type==".JPG" || contents[i].type==".png") filearray.push(contents[i].nativePath);
    return filearray;

    How do i get a list of filenames from the server?

    1. @jacob,

      You would need to use a server side language such as ColdFusion, or PHP to get a directory listing and then return the list of files/attributes to Flash Player using XML or some other format.


  9. Hi all,
    My remote swf file needs to load xml file which is residing outside of war file like property file. When I try with URLRequest, I am getting error like “Remote SWFs may not access local files”. Can anyone help me to resolve this issue please?

Comments are closed.