3 Replies Latest reply on May 29, 2011 11:09 PM by Ztere0

    Read local XML with FileReference




      I have a problem triying to read a local XML file.


      I have this code to get the file from my hd, the file is uploaded correctly, but I don´t know how convert it to XML or String variable.


      The code:


          private var fileRefSave:FileReference = new FileReference();
          private var loader:Loader = new Loader();
          private var xmlFilter:FileFilter = new FileFilter("xml", "*.xml");

           * Click Send buttom
          private function onClickSave(e:MouseEvent):void
            fileRefSave.addEventListener(Event.SELECT, selectedFile);

           * File selected
          private function selectedFile(e:Event):void
            fileRefSave.addEventListener(Event.COMPLETE, loaded);

           * Loaded
          private function loaded(e:Event):void

             // Here I had the proble, I need convert FileReference in XML o String. I try with loader class but doesn´t work.



      thanks. regards.

        • 1. Re: Read local XML with FileReference
          Timothy Brand-Spencer Level 1

          Why are you using FileReference? You need only use this if your application is browser based. It sounds like you are only working with local files, so here is an example using the File class instead.


          var file:File = new File();
          function fileSelectHandler (event:Event) : void
               //get the selected File
               var selectedFile:File = event.target as File;
               //do stuff with the file now, such as read the xml..
          file.addEventListener(Event.SELECT, fileSelectHandler);
          //open file dialog to select file with
          file.browseForOpen("Select an XML File",[xmlFilter]);


          If you really need to use FileReference (i.e. you must have a browser based application), then you should be uploading the selected File to a specific URL, which your example does not seem to do. Please see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference .html#includeExamplesSummary for more information on this.


          Once you have uploaded your file to some URL, your application can then work with the file as it knows where to get it from (the URL where it was uploaded to).



          • 2. Re: Read local XML with FileReference
            blazejewicz Level 4



            You could simply read bytes from returned data into new string converted to XML doc:

            private function loaded(e:Event):void


                 var xml:XML = new XML(fileRefSave.data.readUTFBytes(fileRefSave.data.length));



            (note: you could add error handler - e.g. no bytes for empty 0kb file, enclose xml creation into try/catch to catch TypeError possible exception, etc).



            kind regards,


            • 3. Re: Read local XML with FileReference
              Ztere0 Level 1

              Thx!! it works!