Flex 文件上传导入组件

       上文讲到Flex利用Blazeds来上传文件,本文则封装了一个组件用于文件的上传导入,其主要功能有:

       1)文件的选择;

       2)文件类型的限定,比如只能选择txt文件,图片文件等;

       3)文件上传,利用Blazeds

       4)文件导入,利用Blazeds

       5)上传、导入的事件分发;

 

1、文件上传组件核心代码

<?xml version="1.0" encoding="utf-8"?>

<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"

                    xmlns:s="library://ns.adobe.com/flex/spark"

                    xmlns:mx="library://ns.adobe.com/flex/mx" width="300" height="28" creationComplete="init()">

         <s:layout>

                   <s:BasicLayout/>

         </s:layout>

         <fx:Declarations>

                   <s:RemoteObject id="ro" destination="fileUpDownloadService" result="ro_resultHandler(event)"

                                                        fault="ro_faultHandler(event)"/>

         </fx:Declarations>

         <fx:Metadata>

                   [Event(name="result", type="event.FileImportEvent")]

                   [Event(name="fault", type=" event.FileImportEvent")]

         </fx:Metadata>

         <fx:Script>

                   <![CDATA[

                            import mx.controls.Alert;

                            import mx.messaging.channels.StreamingAMFChannel;

                            import mx.rpc.events.FaultEvent;

                            import mx.rpc.events.ResultEvent;

                            import mx.rpc.remoting.RemoteObject;

                           

                            private var file:FileReference = new FileReference();

                            private var _fileFilter:Array=[];

                            private var ro:Object;

                           

                            protected function init():void{

                                     file.addEventListener(Event.SELECT, selectHandler);

                                     file.addEventListener(Event.COMPLETE, completeHandler);

                            }

                           

                            private function completeHandler(event:Event):void {

                                     //trace("completeHandler: " + event);

                            }

                           

                            private function selectHandler(event:Event):void {

                                     this.txtFileInfo.text = file.name;

                                     this.txtFileInfo.toolTip = "文件大小: "+file.size/1000+ "K";

                                     file.load();  //加载文件

                            }

 

                            /**

                             * 设置文件过滤,打开文件选择框时刻选择哪些类型的文件

                             * FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png")

                             */

                            public function set fileFilter(fileType:String):void{

                                     if(!StringUtil.isEmpty(fileType) && StringUtil.trim(fileType).length>3){

                                               _fileFilter = [];

                                               _fileFilter.push(new FileFilter("("+fileType+")",fileType));

                                     }

                            }

                                                       

                            // Property: maxFileSizeFlash Player Limit 100 mb

                            private var _maxFileSize:Number = 1024*1024*20;

                           

                            [Bindable]

                            /**

                             * 读取和设置文件最大尺寸,单位为Byte,1K = 1024Byte,默认值为20M

                             */

                            public function get maxFileSize():Number

                            {

                                     return _maxFileSize;

                            }

                           

                            public function set maxFileSize(size:Number):void

                            {

                                     _maxFileSize = size;

                            }

                           

                            private function checkFile():Boolean{

                                     var blnResult:Boolean = true;

                                     if(StringUtil.isEmpty(txtFileInfo.text)){

                                               Alert.show("请选择要上传的文件!");

                                               return false;

                                     }

                                     if(file.size>_maxFileSize){    //文件大小验证失败

                                               Alert.show(StringUtil.format("该文件尺寸{0} 超出最大尺寸 {1}.",file.size/1000,_maxFileSize/1000));

                                               blnResult = false;

                                     }

                                     if(file.data==null){

                                               Alert.show("文件正在加载中,请稍等!");

                                               blnResult = false;

                                     }

                                     return blnResult;

                            }

                           

                            protected function btnBrowse_clickHandler(event:MouseEvent):void

                            {

                                     file.browse(_fileFilter); //打开文件选择框

                            }

 

                            protected function btnDelete_clickHandler(event:MouseEvent):void

                            {

                                     //删除远程服务器的文件

                                     //清空txtFileInfo

                                     txtFileInfo.text = "";

                                     txtFileInfo.toolTip = "";

                            }

 

                            protected function ro_resultHandler(event:ResultEvent):void

                            {

                                     this.dispatchEvent(new FileImportEvent(FileImportEvent.RESULT,event.result));

                            }

 

                            protected function ro_faultHandler(event:FaultEvent):void

                            {

                                     this.dispatchEvent(new FileImportEvent(FileImportEvent.FAULT,null,event.fault));

                            }

                           

                            public function importFile(headers:Array):Boolean{

                                     var isSuccess:Boolean = checkFile();

                                     if(isSuccess){

                                               ro.importFile(file.data,headers,file.type);

                                     }

                                     return isSuccess;

                            }

                           

                            public function uploadFile():Boolean{

                                     var isSuccess:Boolean = checkFile();

                                     if(isSuccess){

                                               ro.uploadFile(file.data,file.type);

                                     }

                                     return isSuccess;

                            }

 

                   ]]>

         </fx:Script>

         <s:TextInput left="3" top="3" right="55" id="txtFileInfo" editable="false" bottom="3"/>

         <mx:Button right="29" top="3" label="" width="25" id="btnBrowse" toolTip="选择文件" click="btnBrowse_clickHandler(event)"

                               paddingLeft="3" paddingRight="3" bottom="3" icon = "@Embed('assets/tool_folder_explore.png')"/>

         <mx:Button right="3" top="3" bottom="3" label="" width="25" id="btnDelete" icon = "@Embed('assets/tool_delete.png')"

                               labelPlacement="right" click="btnDelete_clickHandler(event)" paddingLeft="3" paddingRight="3" toolTip="取消文件选择"/>

</s:Group>

2FileImportEvent事件

package event

{

    import flash.events.Event;

   

    import mx.rpc.Fault;

 

    public class FileImportEvent extends Event

    {

       public static const RESULT:String      = "result";

       public static const FAULT:String       = "fault";

       //

       private var _result:Object;

       private var _fault:Fault;

        //

       public function FileImportEvent(type:String, result:Object=null, fault:Fault=null)

       {

           super(type,true);

           this._result = result;

           this._fault = fault;

       }

       //

       public function get result():Object{

           return _result;

       }

       public function set result(value:Object):void{

           _result = value;

       }

       //

       public function get fault():Fault{

           return _fault;

       }

       public function set fault(value:Fault):void{

           _fault = value;

       }

    }

}

 

3、示例

<?xml version="1.0" encoding="utf-8"?>

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"

              xmlns:s="library://ns.adobe.com/flex/spark"

              xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="800" minHeight="600" creationComplete="init()" width="370" height="180"

              xmlns:fileupload="fileupload.*">

    <fx:Script>

       <![CDATA[

           import mx.controls.Alert;

          

           import event.FileImportEvent;

          

          

           protected function init():void{

             

           }

 

           protected function btnUpload_clickHandler(event:MouseEvent):void

           {

              if(importer.checkFile())

                  importer.uploadFile();

           }

 

           protected function importer_resultHandler(event:FileImportEvent):void

           {

              Alert.show("文件上传、导入成功!");

              //如果是文件导入的话,则可通过

              //event.result 获取导入的文件数据

           }

 

           protected function importer_faultHandler(event:FileImportEvent):void

           {

              Alert.show("文件上传、导入失败:"+event.fault.faultString);

           }

 

           protected function btnImport_clickHandler(event:MouseEvent):void

           {

              //当然FileUpDownloadService需增加importFile方法,并增加导入文件的解析

              if(importer.checkFile())

                  importer.importFile(null);

            }

       ]]>

    </fx:Script>

    <fx:Declarations>

       <!--限定只能选择文本文件-->

       <fileupload:FileImporter id="importer" fileFilter="*.txt"

                             result="importer_resultHandler(event)" fault="importer_faultHandler(event)"/>

    </fx:Declarations>

    <s:Button id="btnUpload" click="btnUpload_clickHandler(event)" label="上传" x="89" y="88"/>

    <s:Button id="btnImport" click="btnImport_clickHandler(event)" label="导入" x="182" y="88"/>

</s:Application>

你可能感兴趣的:(function,object,Flex,import,library,文件上传组件)