¿Eres nuevo? ¡Lee el FAQ y ponte al día!
253 visitas

How to load a user-selected file in flash

The FileReference class allows to easily load files selected by a user in Flash. This is how:

1.- Declare a FileReference object:

You need to have the same FileReference object during all the process. From the ActionScript 3.0 reference:

If the FileReference object goes out of scope, any transaction that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload, download, load or save is expected to continue.

To solve it, declare the FileReference object in a place in which it remains in scope. Don't declare it in every function:

ActionScript 3
  1. import flash.net.FileReference;
  2.  
  3. ...
  4.  
  5. var fileReference:FileReference;
  6.  

­

2.- Trigger the event:

Obviously, you need to use a button or something similar so that the user can choose when to load a file. When that event is triggered, this function should be called:

ActionScript 3
  1. protected function loadClicked(e:Event)
  2. {
  3.     fileReference = new FileReference();
  4.  
  5.     // The fileSelected function will be called when the users selects a file
  6.     fileReference.addEventListener(Event.SELECT, fileSelected);
  7.  
  8.     // The browse method receives an array of FileFilters
  9.     fileReference.browse([new FileFilter("XML Files (*.xml)","*.xml")]);
  10. }
  11.  

­

3.- Start to load the file:

When the user chooses a file, the fileSelected function is called:

ActionScript 3
  1. public function fileSelected(event:Event):void
  2. {
  3.     fileReference.addEventListener(Event.COMPLETE, fileLoaded);
  4.  
  5.     fileReference.load();
  6. }
  7.  

­

4.- Get the contents of the file:

Finally, the fileLoaded function is called when the file is successfully loaded:

ActionScript 3
  1. public function fileLoaded(event:Event):void
  2. {
  3.     // fileReference.data contains the contents of the file as a ByteArray
  4.     var content:ByteArray = fileReference.data;
  5.  
  6.    // Use the content of the file as you wish...
  7. }
  8.  

­

The content of these loaded files is usually text or XML. There is other recipe that explains how to convert a ByteArray to text or XML.

Etiquetas: ActionScript 3.0 flash bytearray file FileReference

Insertar: