How to Upload Files in Flex FTP

ftp-128x128 Flex doesn’t support any FTP, but sockets are so cool, you can connect to any type of TCP/IP server, of course FTP. You can always build your server side logic to get your flex app talk to an FTP server to upload files.(In Flash Player 10 you can directly read and write local data.then use Sockets to send this  file to FTP server)

ftp-flex

Following is the source code( You can change the ftp host address, user name and password):

<?xml version=“1.0″ encoding=“utf-8″?>
<mx:Application xmlns:mx=“http://www.adobe.com/2006/mxml”
initialize=“upLoad()” layout=“vertical”> 

<mx:Script>
<![CDATA[ 

import mx.utils.*;
import mx.controls.Alert; 

private var fileRef:FileReference;
private var fileSize:uint;
private var fileContents:ByteArray ;
//you need to initiate two scokets one for sending
//commands and second for sending data to FTP Server
//socket for sending commands to FTP
private    var s:Socket
//responce from FTP
private    var ftpResponce:String;
//socket for sending Data to FTP
private    var dataChannelSocket:Socket;
//responce from FTP when sending Data to FTP
private    var dataResponce:String;
//will hold the IP address of new socket created by FTP
private    var dataChannelIP:String;
//will hold the Port number created by FTP
private    var dataChannelPort:int;
private var user:String=“username”;//FTP usernae
private var pass:String=“password”;//FTP Password 

private function receiveReply(e:ProgressEvent):void{
ftpResponce = s.readUTFBytes(s.bytesAvailable)
var serverResponse:Number = Number(ftpResponce.substr(0, 3));
if(ftpResponce.indexOf(‘227′)>-1){
//get the ip from the string response
var temp:Object = ftpResponce.substring(ftpResponce.indexOf(“(”)+1
,ftpResponce.indexOf(“)”));
var dataChannelSocket_temp:Object = temp.split(“,”);
dataChannelIP = dataChannelSocket_temp.slice(0,4).join(“.”);
dataChannelPort = parseInt(dataChannelSocket_temp[4])*256+
int(dataChannelSocket_temp[5]);
//create new Data Socket based on dataChannelSocket and dataChannelSocket port
dataChannelSocket = new Socket(dataChannelIP,dataChannelPort);
dataChannelSocket.addEventListener(ProgressEvent.SOCKET_DATA, receiveData);
}
//few FTP Responce Codes
switch(String(serverResponse)){
       case “220″ :
                   //FTP Server ready responce
                  break;
       case “331″ :
                 //User name okay, need password
                 break;
    case  “230″:
                  //User  logged in
                break;
    case “250″ :
                //CWD command successful
                break;
       case “227″ :
                     //Entering Passive Mode (h1,h2,h3,h4,p1,p2).
                   break;
      default:
  } 

 //for more please
 //http://http://www.altools.com/image/support/alftp/ALFTP_35_help/
 //FTP_response_codes_rfc_959_messages.htm
traceData(ftpResponce);
} 

private function receiveData(e:ProgressEvent):void{
dataResponce = dataChannelSocket.readUTFBytes(
dataChannelSocket.bytesAvailable);
traceData(“dataChannelSocket_response—>”+dataResponce);
}
private function showError(e:IOErrorEvent):void{
       traceData(“Error—>”+e.text);
}
private function showSecError(e:SecurityErrorEvent):void{
      traceData(“SecurityError–>”+e.text);
    } 

private function createRemoteFile(fileName:String):void{
if(fileName!=null && fileName !=“”){
s.writeUTFBytes(“STOR “+fileName+“\n”);
s.flush();
}
}
private function sendData():void{
fileContents=fileRef.data as ByteArray;
fileSize=fileRef.size;
dataChannelSocket.writeBytes(fileContents,0,fileSize);
dataChannelSocket.flush();
}
//initialize when application load
private function upLoad():void {
fileRef = new FileReference();
//some eventlistener
fileRef.addEventListener(Event.SELECT, selectEvent);
fileRef.addEventListener(Event.OPEN, onFileOpen); 

//this fucntion connect to the ftp server
connect();
//send the usernae and password
this.userName(user);
this.passWord(pass);
//if you want to change the directory for upload file
this.changeDirectory(“/public_html/”);//directory name
//enter into PASSV Mode
s.writeUTFBytes(“PASV\n”);
s.flush();
}
private function onFileOpen(event:Event):void {
} 

private function traceData(event:Object):void {
var tmp:String = “================================\n”;
ta.text +=event.toString()+ “\n” ;
ta.verticalScrollPosition += 20;
}
private function ioErrorEvent(event:IOErrorEvent):void{
Alert.show(“IOError:” + event.text);
}
private function selectEvent(event:Event):void{
btn_upload.enabled = true;
filename.text = fileRef.name;
fileRef.load();
}
private function uploadFile():void {
createRemoteFile(fileRef.name);
sendData();
}
private function connect():void{
s = new Socket(“ftp.yourdomain.com”,21);//Socket(”ftp.anydomain.com”,21);
s.addEventListener(ProgressEvent.SOCKET_DATA, receiveReply);
s.addEventListener(IOErrorEvent.IO_ERROR, showError);
s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, showSecError);
s.addEventListener(Event.CONNECT,onSocketConnect);
s.addEventListener(Event.CLOSE,onSocketClose);
s.addEventListener(Event.ACTIVATE,onSocketAtivate);
}
private function onSocketConnect(evt:Event):void {
//traceData(”OnSocketConnect–>”+evt.target.toString());
}
private function onSocketClose(evt:Event):void {
//traceData(”onSocketClose–>”+evt.target.toString());
}
private function onSocketAtivate(evt:Event):void {
//traceData(”onSocketAtivate–>”+evt.target.toString());
}
private function userName(str:String):void {
sendCommand(“USER “+str);
}
private function passWord(str:String):void {
sendCommand(“PASS “+str);
}
private function changeDirectory(str:String):void {
sendCommand(“CWD “+str);
}
private function sendCommand(arg:String):void {
arg +=“\n”;
s.writeUTFBytes(arg);
s.flush();
}
]]>
</mx:Script>
<mx:Panel id=“up” horizontalAlign=“left” width=“100%” height=“100%”>
<mx:Box width=“100%” height=“100%”>
<mx:VBox >
<mx:Form  width=“449″ height=“284″>
<mx:FormItem label=“Selected File:”>
<mx:Label id=“filename”/>
</mx:FormItem>
<mx:FormItem >
<mx:Button width=“80″ label=“Browse” click=“fileRef.browse()” />
<mx:Button width=“80″ label=“Upload” id=“btn_upload” enabled=“false”
    click=“uploadFile()” />
<mx:Button width=“80″ label=“Cancel” id=“btn_cancel” enabled=“false”
    click=“fileRef.cancel()” />
            </mx:FormItem> 

<mx:HRule width=“100%” tabEnabled=“false”/>
<mx:FormItem label=“Events:”>
<mx:TextArea id=“ta” width=“260″ height=“98″ />
</mx:FormItem>
</mx:Form>
</mx:VBox>
</mx:Box>
</mx:Panel>
</mx:Application>

Following is some other samples:

http://flexonrails.net/?p=9
http://www.onflex.org/ted/2007/05/flexftp-ftp-client-in-flex-using.php

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

61 Responses to “How to Upload Files in Flex FTP”

  1. lala says:

    amount of comments shown how much ppl are into similar stuff.
    any one converted to flex 4 example and would like to share source. lols, i m having difficulty even in copying pasting and testing code. some how quotes “” are creating problem and indentation errors…??

  2. lala says:

    i finally managed to run this with file zilla.
    localftpserver: 127.0.0.1
    user successfully logs in. then i am able to upload 100 mb plus zip files successfully.
    as soon as i change host to live version, it stucks on authenticating user (password) won’t work..
    even i can log it to ftp server via same account information from fireftp or cuteftp… any ideas will really help..

  3. lala says:

    ok, sorry, my bad, its finally working for me on live server. huge thanks for sharing, only problem left is, i am unable to check when file is completely uploaded. and or progress event..
    thanks again..

  4. nick says:

    Hi ,
    i also want to uppload some files to ftp through the flex ,
    please send me the solution.
    my id gourav.flex@gmail.com
    thanks in advance

Leave a Reply