Using the URLVariables and FileReference classes to pass data from Flex to a server-side script
We’ve already seen examples of using Flex to upload and download files (see “Uploading files in Flex using the FileReference class” and “Downloading files in Flex using the FileReference class”), but I’ve seen a lot of bugs/questions centering around the FileReference class lately so thought I’d try and do another example or two.
The following example shows how you can use a combination of the URLVariables, URLRequest, and FileReference classes to pass GET or POST variables to a server-side script while doing a file upload. In this example, we just happen to pass a simple text userID and the user’s Flash Player version, but it should be easy enough to modify the script slightly to pass more unique information to the server (such as a unique user token stored in a SharedObject or a browser cookie). I also added a crude little timer on the example to make it a bit classier.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?> <!-- http://blog.flexexamples.com/2007/10/30/using-the-urlvariables-and-filereference-classes-to-pass-data-from-flex-to-a-server-side-script/ --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" creationComplete="init();"> <mx:Script> <![CDATA[ import flash.net.FileReference; import flash.net.URLRequestMethod; import mx.controls.Alert; import mx.utils.StringUtil; private var fileRef:FileReference; private var urlVars:URLVariables; private var urlReq:URLRequest; private var startTimer:Number; private var timer:Timer; private function init():void { fileRef = new FileReference(); fileRef.addEventListener(Event.SELECT, fileRef_select); fileRef.addEventListener(Event.COMPLETE, fileRef_complete); fileRef.addEventListener(IOErrorEvent.IO_ERROR, fileRef_ioError); urlVars = new URLVariables(); urlVars.userID = 94103; urlVars.fpVersion = flash.system.Capabilities.version; urlReq = new URLRequest(); urlReq.method = URLRequestMethod.POST; urlReq.data = urlVars; urlReq.url = "http://localhost:8300/fileref/uploader.cfm"; timer = new Timer(100); timer.addEventListener(TimerEvent.TIMER, onTimer); } private function onTimer(evt:TimerEvent):void { lbl.text = String(getTimer() - startTimer) + " ms"; } private function start():void { fileRef.browse(); } private function fileRef_select(evt:Event):void { fileRef.upload(urlReq); startTimer = getTimer(); timer.start(); } private function fileRef_complete(evt:Event):void { Alert.show(evt.toString(), evt.type); timer.stop(); } private function fileRef_ioError(evt:IOErrorEvent):void { Alert.show(evt.text, evt.type); timer.stop(); } ]]> </mx:Script> <mx:Button label="upload" click="start();" /> <mx:Label id="lbl" /> </mx:Application>
The previous example just uploads to http://localhost/ (in my case my local JRun server). Since that is pretty much useless 99.8% of the time, you would need to change that URL to your ColdFusion/PHP/ASP/Java upload script on your own server.
If you’re a ColdFusion’er, here’s the script that I use to upload files:
<cfsilent><cfsetting enablecfoutputonly="true" /> <cfset req = getHTTPRequestData( )> <cffile action="UPLOAD" filefield="Filedata" destination="#ExpandPath('.')#" nameconflict="MAKEUNIQUE"> <cfsavecontent variable="info"> <html> <head></head> <body> <cfdump label="CFFILE" var="#cffile#"> <cfdump label="getHTTPRequestData()" var="#req#"> <cfif IsDefined("FORM")> <cfdump label="FORM" var="#FORM#"> </cfif> <cfif IsDefined("URL")> <cfdump label="URL" var="#URL#"> </cfif> </body> </html> </cfsavecontent> <cffile action="WRITE" file="#ExpandPath('./')##cffile.serverFileName#.dump.html" output="#info#" addnewline="Yes"> </cfsilent><cfsetting enablecfoutputonly="false" /> <cfcontent reset="true" /> <cfoutput>fileName=#CFFILE.serverFile#&fileSize=#CFFILE.fileSize#</cfoutput>
It’s a pretty handy script as it not only uploads the file to the server (which is kind of the point), but it also creates a separate HTML file for each upload which tells me things like file names, file size, content length, content type, user agent (“Shockwave Flash”, if you’re curious as to what Flash Player uses for a user agent). It even correctly logs the parameters I passed from Flex to ColdFusion using URLVariables (userID and fpVersion).
For an example of sending variables from a server-side script back to your Flex application after a file upload, see “Using for the FileReference class’s uploadCompleteData event to capture data from a server-side script”.
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.
14 Responses to Using the URLVariables and FileReference classes to pass data from Flex to a server-side script
Leave a Reply Cancel reply
-
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


Thanks for the article.
I have used it to build a similar application in Flash CS3 that has a form for user info as well as a picture. One thing i can’t work out is how to return data back from the post. Is it possible?
I would like to return a string that i can use to determine the outcome of the post.
Cheers
Just spotted the uploadCompleteData event :)
This is great, however an issue i have is that my uploaded file for the form is not obligatory so i have to make two separate calls to the same server page. One with fileReference and one with URLLoader() based on a bool toggled from the fileRefernce SELECT event unless you can think of a better way?
Anyway to parse the file, and store as text variable; Without having to send it a script for the heavy lifting (negate the need to push to remote server at all).
I need to be able to browse local machine, pull in file and parse contents, storing into variable.
thx in advance!
Mason,
This should now be possible in Flash Player 10 using the FileReference class’s new
load()method (I’m not sure if it’s available in newer versions of Flash Player 9). For a rough example, see “Previewing an image before uploading it using the FileReference class in Flash Player 10″.Peter
Ces explications m’ont “débloquées”. Merci!
Thanks. Could not find how to upload data along with file. You made it easy.
Is it possible to use Django to upload the files instead of ColdFusion?????
Squeral,
Sorry, I’ve never used django. You could try asking on FlexCoders and see if anybody there has tried.
Peter
I have been looking for a solution to upload multiple files using Flex and Django but haven’t got any luck yet… :(
Turns out it was easier then I thought… :)
I Just did a upload function, save file service can access anonymously. and save file to a special folder such as “d:\temp”. the all work fine in FireFox,Safari.but IE. the always pop-up login window in IE. whether input right or wrong password,the procedure will failed.
(while I open Fiddler to listen HTTP, the upload becomes OK in IE)
May some errors?
Thanks very much~
How do I upload it on my server with ColdFusion. The combination of ColdFusion and Flex 4.
THX
@Marylka,
There should be a simple example in the comments at “Uploading files in Flex using the FileReference class”.
Peter
Great post, I read it twice.