基于AIR的简单下载工具实现

要用AIR实现一个简单的下载工具还是很容易的,因为AIR为我们提供了访问本地系统文件的API,以下是关键代码:

public static function commonDownload(url:String, file:File, downloadedCallback:Function = null):void
		{
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, function (event:IOErrorEvent):void {
				if(downloadedCallback != null)
					downloadedCallback();
			});
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (event:SecurityErrorEvent):void {
				if(downloadedCallback != null)
					downloadedCallback();
			});
			urlLoader.addEventListener(Event.COMPLETE, function (event:Event):void {
				var bytes:ByteArray = urlLoader.data as ByteArray;
				var fs:FileStream = new FileStream();
				fs.openAsync(file, FileMode.UPDATE);
				fs.writeBytes(bytes, 0, bytes.length);
				fs.addEventListener(Event.COMPLETE, function (event:Event):void {
					fs.close();
				});
				fs.addEventListener(IOErrorEvent.IO_ERROR, function (event:IOErrorEvent):void {
					fs.close();
				});
				if(downloadedCallback != null)
					downloadedCallback();
			});
			urlLoader.load(new URLRequest(url));
		}

其中file为要保存到本地文件的File对象引用,downloadedCallback为回调函数。

一条评论

  1. Ayla说道:

    这个必须赞一个!

留下评论