- How to read binary content of a file in flex
- // ActionScript file
- package source.fileApi{
- import flash.display.Sprite;
- import flash.external.ExternalInterface;
- import flash.system.Security;
- import flash.utils.setTimeout;
- import flash.net.FileReference;
- import flash.net.FileFilter;
- import flash.events.IOErrorEvent;
- import flash.events.Event;
- import flash.utils.ByteArray;
- import mx.utils.URLUtil;
- public class FileAPIMain {
- private var debug:Boolean = false;
- private var dataReaded:String;
- private var fr:FileReference;
- public function FileAPIMain():void{
- ExternalInterface.addCallback("setDebug", setDebug);
- ExternalInterface.addCallback("onLoadFileClick", onLoadFileClick);
- ExternalInterface.call("FileReader.__onFlashInitialized");
- }
- public function log(message:String):void {
- if (debug) {
- ExternalInterface.call("FileReader.__log", encodeURIComponent("[FileReader] " + message));
- }
- }
- public function setDebug(val:Boolean):void {
- debug = val;
- if (val) {
- log("debug enabled");
- }
- }
- public function onLoadFileClick():void{
- //create the FileReference instance
- fr = new FileReference();
- //listen for when they select a file
- fr.addEventListener(Event.SELECT, onFileSelect);
- //listen for when then cancel out of the browse dialog
- fr.addEventListener(Event.CANCEL,onCancel);
- //open a native browse dialog that filters for text files
- fr.browse();
- }
- private function onFileSelect(e:Event):void{
- fr.removeEventListener(Event.SELECT, onFileSelect);
- //listen for when the file has loaded
- fr.addEventListener(Event.COMPLETE, onLoadComplete);
- //listen for any errors reading the file
- fr.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
- //load the content of the file
- fr.load();
- }
- private function onCancel(e:Event):void{
- log("File Browse Canceled");
- fr = null;
- }
- private function onLoadComplete(e:Event):void{
- fr.removeEventListener(Event.COMPLETE, onLoadComplete);
- //get the data from the file as a ByteArray
- var data:ByteArray = fr.data as ByteArray;
- dataReaded = data.readUTFBytes(data.bytesAvailable);
- ExternalInterface.call("FileReader.__getSize", fr.size);
- ExternalInterface.call("FileReader.__getName", fr.name);
- ExternalInterface.call("FileReader.__getData", dataReaded);
- ExternalInterface.call("FileReader.__takeAction");
- //clean up the FileReference instance
- fr = null;
- }
- private function onLoadError(e:IOErrorEvent):void{
- log("Error loading file : " + e.text);
- }
- }
- }