Upload XML into Flex
10 01 2008Today I was asked to add some functionality to a flex application I have been developing, that functionality was to give users the option to upload the XML data file, rather than fetch it from the server. I won’t go in to the details of the application, just that it is completely driven on its data, which is provided via XML. After doing some reading I was surprised to learn that it is not possible to upload an XML file without a server side script of some kind. I choose to use PHP because its quick, easy, and simple. So the concept is that the user sends the file through flex to a server side script, that script accepts the file and returns its contents back to flex as XML.
Here is the flex code:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="275" height="354" creationComplete="init()"> <mx:Script> <![CDATA[ import mx.rpc.events.*; import flash.events.*; import flash.net.FileReference; import flash.net.URLRequest; import flash.net.FileFilter; private var myXML:XML; private var file:FileReference; private function init():void { file = new FileReference(); // Add Event Listners file.addEventListener(Event.SELECT, userSelectedFile); file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, serverResponse); } private function browse():void { file.browse([new FileFilter("XML", "*.XML;")]); } // Called after the user selects the file to upload private function userSelectedFile(event:Event):void { file = FileReference(event.target); file.upload(new URLRequest("file_upload.php"), "FileData", false); } // Called after flex receives response from PHP private function serverResponse(event:DataEvent):void { myXML = XML( event.data ); XML_Box.data = myXML; } ]]> </mx:Script> <mx:VBox> </mx:VBox> <mx:Button id="Upload" label="Upload" click="browse()" x="200" y="322"/> <mx:TextArea id="XML_Box" width="250" height="300" x="12.5" y="10"/> </mx:Application>
Here is the php code:
<?php // Set the header information header ("content-type: text/xml"); // Open the uploaded file $file_handler = fopen($_FILES["FileData"]["tmp_name"], "r"); // Display the file contents while(!feof($file_handler)) { echo fgets($file_handler); } // Close the file fclose($file_handler); ?>
That’s all there is to it! To try it out just click the upload button and select an XML file to upload. If you don’t have an XML file handy you can use this sample file.


Thank you for the code. I was looking for a way to read XML into a Flex app as emitted by a Java servlet. Your example was perfect! Thanks