用AIR实现断点续传

上篇文章讲到了用AIR实现一个简单的的下载工具,但如今的下载工具基本上都支持断点续传,本文就用AIR来实现断点续传。其实也并不是很难,还是用代码说话吧。关键代码如下:

public static function resumeBrokenTransfer(url:String, file:File, downloadedCallback:Function = null):void 
		{
			var request:URLRequest = new URLRequest(url);
			var urlLoader:URLLoader = new URLLoader();
			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(ProgressEvent.PROGRESS, function (event:ProgressEvent):void {
				var bytesTotal:int = urlLoader.bytesTotal;
				urlLoader.close();
				var startPoint:int = getBytesAvailableOfFile(file);
				if(startPoint < bytesTotal)
				{
					var headerItem:URLRequestHeader = new URLRequestHeader("Range", "bytes=" + startPoint + "-" + bytesTotal);
					request.requestHeaders.push(headerItem);
					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.position = startPoint;
						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(request);
				}
				else
				{
					if(downloadedCallback != null)
						downloadedCallback();	
				}
			});
			urlLoader.load(request);
		}

参数说明请参考上一篇文章~

留下评论