<?xml version="1.0" encoding="utf-8"?>
<mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:net="flash.net.*"    
    layout="vertical" fontSize="12" viewSourceURL="srcview/index.html">
    <mx:Script>
    <![CDATA[
        import mx.utils.*;
        import mx.controls.Alert;
        import flash.net.FileReference;
        import flash.net.*;
        import flash.utils.*;
        
        //檔案大小與檔案傳輸類型
        private var fileSize:uint;
        private var fileContents:ByteArray;
        
        //連線用Socket
        private var ftpSocket:Socket;
        private var ftpResponce:String;
        
        //上傳檔案用Socket
        private var upLoadSocket:Socket;
        private var upLoadResponce:String;
        
        //取得使用者的IP與Port
        private var ClientIP:String;        
        private var ClientPort:int;
        
        //連線到FTP資訊
        private var server:String="";//FTP 主機位置ex.ftp.abc.com
        private var user:String="";//FTP 帳號
        private var pass:String="";//FTP 密碼
        private var dir:String="";//FTP 上傳資料夾    
        
        //Ftp連線    
        private function connect():void{
            this.connbtn.enabled=false;
            
            ftpSocket = new Socket(server,21);        
            sendCommand("USER "+this.user);
            sendCommand("PASS "+this.pass);            
            sendCommand("CWD "+dir);
            
            ftpSocket.addEventListener(ProgressEvent.SOCKET_DATA, SocketData);
            ftpSocket.addEventListener(IOErrorEvent.IO_ERROR, IOError);
            ftpSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, SecError);
            
            ftpSocket.addEventListener(Event.CONNECT, SocketConn);
            ftpSocket.addEventListener(Event.CLOSE, SocketClose);
            ftpSocket.addEventListener(Event.ACTIVATE, SocketAtivate);            
        }
        
        private function SocketData(e:ProgressEvent):void{
            ftpResponce = ftpSocket.readUTFBytes(ftpSocket.bytesAvailable)
            var serverResponse:Number = Number(ftpResponce.substr(0, 3));
            
            if(ftpResponce.indexOf('227')>-1){
                //取得使用者的ip位置
                var temp:Object = ftpResponce.substring(ftpResponce.indexOf("(")+1 ,ftpResponce.indexOf(")"));
                var upLoadSocket_temp:Object = temp.split(",");
                ClientIP = upLoadSocket_temp.slice(0,4).join(".");
                ClientPort = parseInt(upLoadSocket_temp[4])*256+
                int(upLoadSocket_temp[5]);
                
                //建立一個上傳的PORT
                upLoadSocket = new Socket(ClientIP,ClientPort);
                upLoadSocket.addEventListener(ProgressEvent.SOCKET_DATA, receiveData);
            }
                
            switch(String(serverResponse)){
                case "220": //FTP連線就續
                    break;                    
                
                case "331"://帳號ok,密碼錯誤
                    break;
                    
                case "230"://登入成功
                        //指定下載文件的類型,I是二進位文件,A是字元文件            
                        sendCommand("TYPE A");//設定TYPE為ASCII
                        sendCommand("TYPE I");//設定上傳的編碼為8-bit binary                    
                        sendCommand("PASV");//passive模式
                    break;
                    
                case "250" ://資料夾切換成功
                    break;
                    
                case "227" : //Entering Passive Mode (h1,h2,h3,h4,p1,p2).
                    break;
                default:
             }
            traceData(ftpResponce);
        }         
        
        private function IOError(e:IOErrorEvent):void{
           traceData("—>Error:"+e.text);
        }
        
        private function SecError(e:SecurityErrorEvent):void{
           traceData("–>SecurityError:"+e.text);
        } 
        
        private function SocketConn(evt:Event):void {
            traceData("–>OnSocketConnect:"+evt.target.toString());
        }
                        
        private function SocketAtivate(evt:Event):void {
            traceData("–>onSocketAtivate");
            sendCommand("PWD");
            ftpSocket.flush();        
        }
        
        private function SocketClose(evt:Event):void {            
            traceData("–>onSocketClose");
            sendCommand("REST 0");
            sendCommand("PWD");
            ftpSocket.flush();                        
        }
        
        //ProgressEvent.SOCKET_DATA
        private function receiveData(e:ProgressEvent):void{
            upLoadResponce = upLoadSocket.readUTFBytes(upLoadSocket.bytesAvailable);
            traceData("upLoadSocket_response—>"+upLoadResponce);
        }
        
        //瀏覽檔案            
        private function selectEvent(event:Event):void{
            upLoadbtn.enabled = true;
            this.filename.text = fileRef.name;
            fileRef.load();
        }
                    
        //檔案上傳
        private function uploadFile():void {
            createRemoteFile(fileRef.name);//下上傳指令
            sendData();//送出檔案
        }
        
    
        private function createRemoteFile(fileName:String):void{
            if(fileName!=null && fileName !=""){                
                sendCommand("STOR "+fileName);//上傳指令
                ftpSocket.flush();
            }
        }
        
        //檔案轉二進位傳送
        private function sendData():void{
            fileContents=fileRef.data as ByteArray;
            fileSize=fileRef.size;
            upLoadSocket.writeBytes(fileContents,0,fileSize);
            upLoadSocket.flush();
        }
            
        //處理Ftp指令
        private function sendCommand(arg:String):void {
            arg +="\n";
            ftpSocket.writeUTFBytes(arg);
            ftpSocket.flush();
        }
        
        //顯示資訊
        private function traceData(event:Object):void {
            var tmp:String = "================================\n";
            infotxt.text +=event.toString()+ "\n" ;
            infotxt.verticalScrollPosition += 20;            
        }
    ]]>
    </mx:Script>
    <net:FileReference id="fileRef"    select="selectEvent(event)"/>    
         
    <mx:Panel id="up" horizontalAlign="left" width="100%" height="100%">
        <mx:Box width="100%" height="100%">
            <mx:VBox>            
                <mx:Form>
                    <mx:FormItem label="Selected File:">
                        <mx:Label id="filename"/>
                    </mx:FormItem>
                    
                    <mx:FormItem >
                        <mx:Button width="80" label="連線" id="connbtn" click="connect();" />
                        <mx:Button width="80" label="瀏覽" click="fileRef.browse()" />
                        <mx:Button width="80" label="上傳" id="upLoadbtn" enabled="false"
                            click="uploadFile()" />
                    </mx:FormItem> 
        
                    <mx:HRule width="100%" tabEnabled="false"/>
                    <mx:FormItem label="Events:">
                        <mx:TextArea id="infotxt" width="331" height="124" />                        
                    </mx:FormItem>
                </mx:Form>
            </mx:VBox>
        </mx:Box>
    </mx:Panel>
</mx:Application>