Here is a utility class for downloading resource and saving as file asynchronously.
Here is the usage for this utility class.
package utils.file
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.ProgressEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
public class AsyncFileSaveDownloader extends EventDispatcher
{
public function AsyncFileSaveDownloader()
{
}
public function download(url:String, path:String):void {
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, completeDownload);
loader.load(new URLRequest(url));
function completeDownload(cevt:Event):void
{
loader.removeEventListener(Event.COMPLETE, completeDownload);
var file:File = new File(path);
var fs:FileStream = new FileStream();
fs.addEventListener(Event.CLOSE, completeSave);
fs.openAsync(file, FileMode.WRITE);
fs.writeBytes(cevt.target.data);
fs.close();
function completeSave(sevet:Event):void {
fs.removeEventListener(Event.CLOSE, completeSave);
dispatchEvent(new FileDownloadEvent(url, path, FileDownloadEvent.SAVE_CONPLETE));
}
}
}
}
}
package utils.file
{
import flash.events.Event;
public class FileDownloadEvent extends Event
{
public static const SAVE_CONPLETE:String = "SaveComplete";
private var _url:String;
private var _path:String;
public function FileDownloadEvent(url:String, path:String, type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this._url = url;
this._path = path;
}
public override function clone():Event
{
return new FileDownloadEvent(_url, _path, type, bubbles, cancelable);
}
public override function toString():String
{
return formatToString("FileDownloadEvent", "type", "bubbles", "cancelable", "eventPhase");
}
public function get url():String {
return _url;
}
public function get path():String {
return _path;
}
}
}
Here is the usage for this utility class.
package utils.file
{
import flash.display.Sprite;
import flash.text.TextField;
public class Test extends Sprite
{
private var text:TextField = new TextField();
public function Test()
{
text.text = "start downloading";
addChild(text);
var downloader:AsyncFileSaveDownloader = new AsyncFileSaveDownloader();
downloader.addEventListener(FileDownloadEvent.SAVE_CONPLETE, function(e:FileDownloadEvent):void {
text.text = "download complete!!";
});
downloader.download("http://www.google.com/", "c:/temp/test.html");
}
}
}
コメント