1 Reply Latest reply on Jun 26, 2008 9:00 AM by matthew horn

    Flex file uploader component

    sanjeev rajput
      Hi,
      this is a fully running flex based file upload component this component allow you to upload any file on any user specific server url you can control upload functionality by java script or you can use upload button available in this comtrol.

      there are few steps which you need to follow.
      1. create a new project named it [FileUploaderControlls] () you can user your name
      2. Put following code in main XML file.
      <?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml" layout="absolute" initialize="initApp()" width="365" height="35" verticalScrollPolicy="off" horizontalScrollPolicy="off" backgroundAlpha="0">
      <mx:Script>
      <![CDATA[
      import mx.managers.PopUpManager;
      import mx.controls.Alert;
      private var _refUploadFile:FileReference;
      private var _winProgress:winProgress;
      private function initApp():void{
      _refUploadFile=new FileReference();
      initBaseItem()
      }
      private function initBaseItem():void{
      _refUploadFile.addEventListener(Event.SELECT, selectEventHandler);
      if (ExternalInterface.available)
      ExternalInterface.addCallback("uploadFile", uploadFile);
      Security.allowDomain("*");
      fileName.editable=false;
      }
      private function initEvents():void{
      _refUploadFile.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
      _refUploadFile.addEventListener(Event.COMPLETE, onUploadComplete);
      _refUploadFile.addEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
      _refUploadFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);

      }
      // Cancel and clear eventlisteners on last upload
      private function disposeAll():void {
      _refUploadFile.removeEventListener(ProgressEvent.PROGRESS, onUploadProgress);
      _refUploadFile.removeEventListener(Event.COMPLETE, onUploadComplete);
      _refUploadFile.removeEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
      _refUploadFile.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
      _refUploadFile.cancel();
      }

      private function selectEventHandler(event:Event):void{
      fileName.text=_refUploadFile.name;
      _refUploadFile=FileReference(event.target);
      }

      private function browseFile():void{
      _refUploadFile.browse();
      }

      private function uploadFile(serverLocation:String, file:String):void{
      // Variables to send along with upload
      initEvents();
      var request:URLRequest=new URLRequest(serverLocation);
      request.method=URLRequestMethod.POST;
      try
      {
      _winProgress = winProgress(PopUpManager.createPopUp(this, winProgress, true));
      PopUpManager.centerPopUp(_winProgress);
      _winProgress.btnCancel.removeEventListener("click", onUploadCanceled);
      _winProgress.btnCancel.addEventListener("click", onUploadCanceled);
      //var _refUploadFile:FileReference=FileReference(selectedFileRef);
      _refUploadFile.upload(request, file, false);
      }
      catch (error:Error)
      {
      throw new Error("Unable to upload file.");
      }
      }
      // Called on upload cancel
      private function onUploadCanceled(event:Event):void {
      PopUpManager.removePopUp(_winProgress);
      _winProgress == null;
      _refUploadFile.cancel();
      disposeAll();
      }

      // Get upload progress
      private function onUploadProgress(event:ProgressEvent):void {
      var numPerc:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
      _winProgress.progBar.setProgress(numPerc, 100);
      //_winProgress.progBar.label = numPerc + "%";
      _winProgress.progBar.label = event.bytesLoaded +" of " + event.bytesTotal;
      _winProgress.progBar.validateNow();
      if (numPerc > 90) {
      _winProgress.btnCancel.enabled = false;
      } else {
      _winProgress.btnCancel.enabled = true;
      }
      }

      // Called on upload complete
      private function onUploadComplete(event:Event):void {
      PopUpManager.removePopUp(_winProgress);
      ErrorAlert.show("Upload successful", false);
      ExternalInterface.call("uploadStatus", "file uploaded");
      }

      // Called on upload io error
      private function onUploadIoError(event:IOErrorEvent):void {
      ErrorAlert.show("IO Error in uploading file.", true);
      PopUpManager.removePopUp(_winProgress);
      _winProgress == null;
      _refUploadFile.cancel();
      disposeAll();
      }

      // Called on upload security error
      private function onUploadSecurityError(event:SecurityErrorEvent):void {
      ErrorAlert.show("Security Error in uploading file.", true);
      PopUpManager.removePopUp(_winProgress);
      _winProgress == null;
      disposeAll();
      }

      ]]>
      </mx:Script>
      <mx:HBox width="100%" height="100%" verticalAlign="middle" horizontalAlign="left" horizontalGap="2" paddingLeft="5" paddingRight="5">
      <mx:TextInput x="0" y="0" id="fileName" width="220"/>
      <mx:Button x="165" y="0" label="Browse" click="browseFile()"/>
      <mx:Button label="Upload" id="btnUpload" click="uploadFile('your domain name','file')"/>
      </mx:HBox>
      </mx:Application>
      3. Create a new MXML loader component named it [winProgress.mxml] with following code.
      <?xml version="1.0" encoding="utf-8"?>
      <mx:VBox xmlns:mx=" http://www.adobe.com/2006/mxml" width="250" height="30" verticalGap="0" verticalAlign="middle" backgroundColor="#d7d3b5">
      <mx:HBox horizontalAlign="left" verticalAlign="middle" paddingLeft="5" paddingRight="5" horizontalGap="5" width="100%" horizontalScrollPolicy="off" height="18">
      <mx:ProgressBar width="210" id="progBar" mode="manual" labelPlacement="right" fontFamily="Verdana" fontSize="8" color="#000000"/>
      <mx:Button label="X" id="btnCancel" width="20"/>
      </mx:HBox>
      <mx:Label id="txtByteInfo" width="100%" height="15"/>
      </mx:VBox>

      4. Create one more component as alert component named it [ErrorAlert.mxml] use following code.
      <?xml version="1.0" encoding="utf-8"?>
      <mx:HBox xmlns:mx=" http://www.adobe.com/2006/mxml" width="300" height="22" backgroundColor="#d7d3b5" verticalAlign="middle" horizontalAlign="left">
      <mx:Label id="txtErr" text="{_errMsg}" width="100%" color="#000000"/>
      <mx:Button id="btnOk" label="OK" click="removeMe()" visible="{_showButton}"/>
      <mx:Script>
      <![CDATA[
      import mx.managers.PopUpManager;
      import mx.core.ApplicationGlobals;
      [Bindable]
      private var _showButton:Boolean=false;
      [Bindable]
      private var _errMsg:String=null;
      private static var _me:ErrorAlert=null;
      private static function popup() : void {
      _me = ErrorAlert(PopUpManager.createPopUp(Sprite(ApplicationGlobals.application), ErrorAlert, true));
      PopUpManager.centerPopUp(_me);
      }

      private function removeMe():void{
      PopUpManager.removePopUp(_me);
      }
      public static function show(errMsg:String, showButton:Boolean = false) : void {
      if (_me == null) {
      popup();
      }
      _me._showButton=showButton;
      _me._errMsg=errMsg;
      }
      ]]>
      </mx:Script>
      </mx:HBox>
      5. Compile main MXML file
      6. you are ready to go...

      Enjoy !