flex 下載文件

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>

不過要記得打開自己的服務器,把下載的文件放上去

發佈了27 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章