flex中下载文件
下载文件是很简单的,使用这个FileReference类即可,3行代码即可,在实验中发现没有反应,在反复测试中终于找到了原因。
在flex中下载文件是异步的,你要把FileReference类的生存周期设的更长一下才可以。
下面把代码贴出来
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="#f6f6f6" backgroundGradientColors="[#f6f6f6, #bbbbbb]">
<mx:Label x="10" y="10" text="Download File" fontSize="20" fontWeight="bold"/>
<mx:HRule x="10" y="49" width="80%"/>
<mx:Button x="10" y="75" label="Download HTML Component" click="{download()}"/>
<mx:Script>
<![CDATA[
private var downloadURL:URLRequest;
private var file:FileReference; //这是要主要的地方
public function download():void {
downloadURL = new URLRequest("http://localhost/flex/1.html.bak");
file = new FileReference();
configureListeners(file);
file.download(downloadURL);
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.CANCEL, cancelHandler);
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(Event.SELECT, selectHandler);
}
private function cancelHandler(event:Event):void {
trace("cancelHandler: " + event);
}
private function completeHandler(event:Event):void {
trace("completeHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
private function openHandler(event:Event):void {
trace("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
var file:FileReference = FileReference(event.target);
trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
private function selectHandler(event:Event):void {
var file:FileReference = FileReference(event.target);
trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url);
}
]]>
</mx:Script>
</mx:Application>
不过要记得打开自己的服务器,把下载的文件放上去