I wrote a utility class for loading bytes from URL because the official method needs a lot of preparation.
Here is the usage.
Here is the core code.
This is the ByteLoadEvent class.
Here is the usage.
var loader:ByteLoadHelper = new ByteLoadHelper(); loader.addEventListener(ByteLoadEvent.COMPLETE, completeHandler); loader.load(url); function completeHandler(evt:ByteLoadEvent):void { loader.removeEventListener(ByteLoadEvent.COMPLETE, completeHandler); var bytes:ByteArray = evt.data; // do something nice :D }
Here is the core code.
package utils.tool { import flash.events.Event; import flash.events.EventDispatcher; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.utils.ByteArray; public class ByteLoadHelper extends EventDispatcher { public function ByteLoadHelper() { } public function load(url:String):void { var urlLoader:URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoaderDataFormat.BINARY; urlLoader.addEventListener(Event.COMPLETE, loadComplete); try { urlLoader.load(new URLRequest(url)); } catch (e:Error) { // ideally you should do some error handling urlLoader.removeEventListener(Event.COMPLETE, loadComplete); } } protected function loadComplete(e:Event):void { var urlLoader:URLLoader = e.currentTarget as URLLoader; urlLoader.removeEventListener(Event.COMPLETE, loadComplete); dispatchEvent(new ByteLoadEvent(ByteLoadEvent.COMPLETE, urlLoader.data, false, false)); } } }
This is the ByteLoadEvent class.
package utils.tool { import flash.events.Event; import flash.utils.ByteArray; public class ByteLoadEvent extends Event { public static const COMPLETE:String = "complete"; private var _data:ByteArray; public function ByteLoadEvent(type:String, data:ByteArray, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); this._data = data; } public override function clone():Event { return new ByteLoadEvent(type, _data, bubbles, cancelable); } public override function toString():String { return formatToString("ByteLoadEvent", "type", "bubbles", "cancelable", "eventPhase"); } public function get data():ByteArray { return _data; } } }
コメント