AS3中FileRefence类提供了上传和下载文件的方法,它可以打开一个对话框供用户用于上传和下载文件的位置,做了一个简单的文件下载程序练习下FileRefence类中方法和事件的使用。

先在舞台上添加一个输入文本框,一个progressBar组件和两个按钮,命名为"fileURL","downloadProgress","download","cancel";

然后开始编写代码:

var fr:FileReference = new FileReference();
fileURL.text = "http://www.okxs.net/upload/IMG_1237.jpg"
fr.addEventListener(Event.OPEN,openHandler);
fr.addEventListener(ProgressEvent.PROGRESS,progressHandler);
fr.addEventListener(Event.COMPLETE,completeHandler);
fr.addEventListener(IOErrorEvent.IO_ERROR,ioerrorHd);
download.addEventListener(MouseEvent.CLICK,startDownload);
cancel.addEventListener(MouseEvent.CLICK,cancelDownload);

function cancelDownload(event:MouseEvent):void {
 fr.cancel();
 download.enabled = false;
}

function startDownload(event:MouseEvent):void {
 var request:URLRequest = new URLRequest();
 request.url = fileURL.text;
 fr.download(request);
}

function openHandler(event:Event):void {
 download.enabled = true;
 trace("open");
}
//下载处理函数,用进度条显示下载速度
function progressHandler(event:ProgressEvent):void {
 downloadProgress.setProgress(event.bytesLoaded,event.bytesTotal);
 trace("prog");
}

function completeHandler(event:Event):void {
 downloadProgress.setProgress(0,100);
 download.enabled = false;
 trace("ok");
}

function ioerrorHd(event:IOErrorEvent) {
 trace("不能下载该文件");
}

点击下载按钮后程序读取文本框中的地址,创建URLRequest对象,调用download()方法实现下载。

我内心激动,有话要说