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()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var VARIABLES_URL:String = "params.txt";
[Bindable]
private var arrColl:ArrayCollection;
[Bindable]
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);
urlLdr.load(urlReq);
}
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;
break;
}
}
]]>
</mx:Script>
<mx:VBox>
<mx:Label text="Events:" />
<mx:DataGrid id="events" dataProvider="{arrColl}" rowCount="5">
<mx:columns>
<mx:DataGridColumn dataField="idx" headerText="#" width="20" />
<mx:DataGridColumn dataField="type" headerText="Type" showDataTips="true" dataTipField="eventString" />
</mx:columns>
</mx:DataGrid>
</mx:VBox>
<mx:VBox>
<mx:Label text="Parameters:" />
<mx:DataGrid id="params" dataProvider="{paramColl}" rowCount="5" visible="false">
<mx:columns>
<mx:DataGridColumn dataField="key" headerText="Key" />
<mx:DataGridColumn dataField="value" headerText="Value" />
</mx:columns>
</mx:DataGrid>
</mx:VBox>
</mx:Application>
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
15 Responses to Loading files using the URLLoader and URLVariables classes
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


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
I’ve been searching for solution on unload the data loaded using URLLoader by clicking a checkbox. Any help will be appreciated. Thanks.
this was helpful to me. I’m new to Flex and reading code that uses the URLLoader helps.
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.
Thanks,
Dharmendra
Hi Dharmendra,
I have some requirement like you have. Please let me know, if you find any solution.
Regards,
Krishna
Can i set this [Bindable]
private var VARIABLES_URL:String = “params.txt”;
to a php page?
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]});
}
with:
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.
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?
hey guys,
why dont u just show any simple example about URLLoader instead of this nauseous code?
This is as simple as it get AlCapone
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()
Your probably using this line of code:
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
Right?
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”.
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?
@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.
Peter
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?