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. away4m says:

    in local it’s worked properly but when i upload in server i couldn’t make it work.what i need to do ? i think i have some crossdomain.xml related problems …

  2. lg3 says:

    Can you modify this to do WebDAV?

  3. Moshiur says:

    For away4m:

    CrossDomain issue, please download this java applet and let it run on the server which you are calling. This this handle the security issue.

    http://www.flash-resources.net/download.html

  4. Hi. Thanks for your code. But I was wondering if you could transfer raw text and have it saved as a file instead of transferring a file instead.

    I replaced the following in your sendData method from

    fileContents=fileRef.data as ByteArray;
    fileSize=fileRef.size;
    dataChannelSocket.writeBytes(fileContents,0,fileSize);
    dataChannelSocket.flush();

    to

    var text:String = textField.text;
    var ba:ByteArray = new ByteArray();
    ba.writeUTFBytes(text);
    dataChannelSocket.writeBytes(ba,0,ba.length);
    dataChannelSocket.flush();

    But couldnt get it to work

  5. Michael says:

    I’m trying to get this to work, but I’m getting two compiler errors:

    1061: Call to a possibly undefined method load through a reference with static type flash.net:FileReference

    1119: Access to possibly undefined property data through a reference with static type flash.net:FileReference

    I know this is probably an easy fix, but could someone point me in the right direction? Thanks.

  6. Michael says:

    Turns out FileReference.data and FileReference.load() are FP10 only so targeting 10 fixed everything. Thanks for the awesome example.

  7. Fredrik says:

    Hi,

    The upload is working for me but the receiveData method is never fired. So I don’t know when the file is uploaded.
    Any ideas?

  8. Sofer says:

    Following is the same upload I got from google. Enjoy!!!

    <?xml version=”1.0″ encoding=”utf-8″?>
    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”

    initialize=”upLoad()” layout=”vertical” viewSourceURL=”srcview/index.html”>

    <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 host:String='xxxxx.sample.com'; //FTP host
    private var user:String="xxxxx";//FTP usernae
    private var pass:String="xxxxx";//FTP Password
    private var workingDir:String = '/'; //Default is FTP Root folder...

    private function receiveReply(event:ProgressEvent):void{
    ftpResponce = s.readUTFBytes(s.bytesAvailable);

    var serverResponse:Number = Number(ftpResponce.substr(0, 3));
    traceData(ftpResponce);
    //traceData('CODE:x ' +String(serverResponse));

    //few FTP Responce Codes
    switch(serverResponse){
    case 220 :
    //FTP Server ready responce
    this.userName(user);

    break;
    case 331 :
    //User name okay, need password
    this.passWord(pass);
    //sendCommand("SYST");
    //sendCommand("FEAT");
    sendCommand("OPTS UTF8 ON");
    //sendCommand("OPTS MLST type:size;modify;perm");

    break;
    case 230:
    //User logged in
    //if you want to change the directory for upload file
    this.changeDirectory(workingDir); //directory name

    break;
    case 200 :
    //CWD command successful
    //switch to passive mode.
    //this.sendCommand('TYPE I');
    this.sendCommand('PASV');

    break;
    case 250 :
    //CWD command successful
    //switch to passive mode.
    this.sendCommand('TYPE I');
    //this.sendCommand('PASV');

    break;
    case 226 :
    //CWD command successful
    //switch to passive mode.
    //this.sendCommand('TYPE I');
    this.sendCommand('PASV');
    //this.sendCommand('MLSD');

    break;
    case 227 :
    //Entering Passive Mode (h1,h2,h3,h4,p1,p2).
    //get the ip from the string response... this lets us set up our data connection...
    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.timeout(200000);
    dataChannelSocket.addEventListener(ProgressEvent.SOCKET_DATA, receiveData);
    dataChannelSocket.addEventListener(ProgressEvent.PROGRESS, progressHandler2);
    //traceData(“Setting 227\n”);

    break;
    case 150:

    sendData();
    break;
    default:
    //this.sendCommand(‘PASV’);

    }

    if (serverResponse >= 500)
    {
    this.sendCommand(‘PASV’);
    }
    }

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

    private function createRemoteFile(fileName:String):void{
    if(fileName!=null && fileName !=”"){
    s.writeUTFBytes(“STOR “+fileName+”\r\n”);
    traceData(“–>STOR “+fileName+”\r\n”);
    s.flush();

    }
    }

  9. Sofer says:

    private function progressHandler2(e:ProgressEvent):void {
    // update the ProgressBar
    trace(“e.bytesLoaded:["+e.bytesLoaded+"], e.bytesTotal:["+e.bytesTotal+"]“);
    // myProgress.setProgress(e.bytesLoaded,e.bytesTotal);
    }

    private function sendData():void{
    //myProgress.visible = true;
    fileContents=fileRef.data as ByteArray;
    fileSize=fileRef.size;
    //s.readBytes(fileContents, 0,fileSize);

    //dataChannelSocket.writeUTFBytes(fileContents);
    dataChannelSocket.writeBytes(fileContents);
    dataChannelSocket.flush();
    dataChannelSocket.close();
    /*dataChannelSocket.writeBytes(fileContents,0,fileSize);
    dataChannelSocket.flush();
    dataChannelSocket.close();
    btn_upload.enabled = false;
    */
    //s.flush();
    //traceData(“SendData>”+fileSize);
    }

    //initialize when application load
    private function upLoad():void {
    //fileRef = new FileReference();
    //some eventlistener
    //fileRef.addEventListener(Event.COMPLETE, onLoadComplete);
    //fileRef.addEventListener(Event.SELECT, selectEvent);
    //fileRef.addEventListener(Event.OPEN, onFileOpen);

    //this fucntion connect to the ftp server
    connect();
    /*should do the following:
    connect
    send user
    send pass
    change working directory.
    go pasv -> sets up data socket.
    */
    }

    private function onReadFile(event:MouseEvent):void
    {
    fileRef = new FileReference;
    fileRef.addEventListener(Event.COMPLETE, onLoadComplete);
    fileRef.addEventListener(Event.SELECT, selectEvent);
    fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
    fileRef.browse();
    }

    private function onLoadComplete(event:Event):void
    {
    fileRef.removeEventListener(Event.COMPLETE, onLoadComplete);
    fileRef.removeEventListener(Event.SELECT, selectEvent);
    //fileRef.removeEventListener(ProgressEvent.PROGRESS, progressHandler);

    btn_upload.enabled = true;
    //Alert.show(_fileRef.data.readUTFBytes(_fileRef.data.length).toString());
    }

    private function progressHandler(event:ProgressEvent):void
    {
    trace (“Progress: ” + event.bytesLoaded);
    pb.setProgress(event.bytesLoaded, event.bytesTotal);
    }

    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{
    //var fileRef:FileReference = event.target as FileReference;

    filename.text = fileRef.name;
    fileByte.text = fileRef.size.toString();

    fileRef.load();

    }

    private function uploadFile():void {
    createRemoteFile(fileRef.name);

    }

    private function connect():void{
    s = new Socket(host,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,onSocketActivate);
    }
    private function onSocketConnect(evt:Event):void {
    //traceData(“OnSocketConnect>”+evt.target.connected.toString());
    }
    private function onSocketClose(evt:Event):void {
    //traceData(“onSocketClose>”+evt.target.toString());
    }
    private function onSocketActivate(evt:Event):void {
    //traceData(“onSocketActivate>”+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 +=”\r\n”;
    s.writeUTFBytes(arg);
    s.flush();
    }

    ]]>

  10. Fredrik says:

    Thanks!

    My code fired “dataChannelSocket” before Passive Mode was ready!
    If I wait until Passive Mode is active and fire the second socket (“dataChannelSocket”) the addEventListener is fired.

    Just need to restructure my code.

    Nice.

  11. Fredrik says:

    Hmm, I was to fast with my assumption.
    The progressHandler2 is never triggered.

    So I am back to square one :-(

  12. Fredrik says:

    Sofer I don’t think your code works. If I upload files larger the 13kb the socket is closed and the uploaded file corrupt.

  13. jp says:

    Hi,
    Thanks for the upload to ftp code. But I am getting this Security error – 2048. I’ve uploaded the cross-domain.xml to my ftp account but still get the same error.
    I’ve used alert boxes to test where the error is.

    private function sendData():void{
    Alert.show(“4″)
    fileContents=fileRef.data as ByteArray;

    fileSize=fileRef.size;
    Alert.show(“5″)

    dataChannelSocket.writeBytes(fileContents,0,fileSize);

    dataChannelSocket.flush();

    }

    I guess it doesn’t go beyond the alert 5 msg.

    Could you help me with this.

    Thanks a ton!

  14. Fredrik says:

    Hi jp,

    Try to see if any tips on this page helps:
    http://teknograd.wordpress.com/2009/11/10/cross-domain-policy-and-sockets/

    Best regards Fredrik

  15. jp says:

    Hi Fredrik,
    Thanks for your prompt reply.
    I’ve gone the links you sent and I changed couple of things. Then I got the debugger version of Flash which showed me the following error-

    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    After going through the code I guess its the dataChannelSocket thats empty because I don’t get the Alert messages from receiveReply function.

    Can you still help me?

    Thanks again Fredrik!
    jp

  16. Fredrik says:

    Hi JP,

    Happy if I can be of some help.
    However we are a bit to deep into AS3 for me now ;-) .

    But if you are not getting anything back from dataChannelSocket it seems to be e remote error (FTP).
    What helped me was to go through the steps manually via telnet.
    Basically I did a telnet server_exemple.com 21 and entered step by step the FTP commands.
    But as you are not getting anything back from dataChannelSocket I would guess that you wont even get anything from telnet as it might be a FW or network problem.

    Best regards Fredrik

  17. rkstar says:

    The dataChannelSocket will never fire a ProgressEvent because it does not send data back. This is a write-only socket. If you telnet to your server on port 21, then use PASV and open a second telnet session to your server with the appropriate data port you can write to it and the data is stored in your file, but there is no feedback.

    Here are the steps:

    #> telnet mydomain.com 21
    connected…
    USER anonymous

    password req’d…
    PASS a@b.c

    user ok…
    PASV

    passive mode entered (127,0,0,1,123,44)
    STOR somenewfile.txt

    ===================
    At this point, you’ll have to open a new telnet session at mydomain.com

    Your FIRST telnet session will show:
    “150: data connection opened for somenewfile.txt”

    Now when you start typing in your SECOND (data) telnet session, your text will be written to somefile.txt every time to press . To quit the data session use ctrl+] (or whatever escape char it tells you). When you quit the data session you’ll get another message on your FIRST (control) telnet session saying:
    “226: transfer completed”

    This is what you need to get your AS sockets to duplicate.
    ===================

    As far as tracking progress of the upload, you can’t do it with these sockets alone. What I did to get around this was I created a small bash script on my server that listens to a specified port. I open another AS socket on that port and send it the filename I’m currently uploading. The listener determines the path to the file and gets the size and sends it back to the AS client. Set that up on a Timer and Bob’s your uncle.

    To solve the crossdomain (security sandbox) issue, I downloaded a Flash Policy Server that’s written in Python. It listens on port 843 (default flash policy port) and serves up the policy goodness whenever my app connects.

  18. bill says:

    Hi Fredrik,
    Thank you for your code.But I got a strange problem.I just can receive the first msg form the http://FTP.It is “welcome to …”,but no reply when sending the user name,password and so on.So I think It is not the FW or the network problem,because I can receive data from the server.
    Can you give me some suggestions?
    Thanks.

  19. Fredrik says:

    Hi Bill.

    You probably read what rkstar wrote. The best thing to reverse engineer FTP is to test the workflow through basic telnet.

    But what I have seen is that different FTP servers handle carriage return different.
    Try to send \n or \r\n as end of line. Some FTP servers need the full \r\n.

  20. jpone says:

    Hi

    Im a newbie, thanks for your great work. But can you let me know which protocol based? FTP protocol?

  21. bill says:

    Thank you for your quick reply.
    It’s just the key.Thanks a lot.
    I find when I try to upload a 180M file,It failed.Can I split the file to several parts and upload them one by one?
    Do you have some idea about it?

  22. jpone says:

    Hi, bill

    I think you should try “transmission resuming at break-points”. Because ftp success or failed, not only based the program, but also your network. :)

  23. Fredrik says:

    Hi Bill,

    I have not tried to split a file and I am not sure if thats a good idea. Then you need to make sure that you put the file together again in the right order.

    I assume that it all works when you use a “normal” FTP client.

    This is a wild guess, but small files work?

    What I found out is that Adobe is sending the file as non-blocking. This means that the script wont wait until the transfer is done. And on top of this it wont fire a OutputProgressEvent or any other event when done.
    So you will not know when the transfer is done!
    Read my post on it http://teknograd.wordpress.com/2009/10/14/flex-socket-sucks/.

    What I did was to make sure that the FTP server uses the original filename during upload (some FTP servers change uses a tmp name). I then call a PHP script on the FTP server (well through HTTP ;-) from the Flex app every 5 seconds and check to see if the sent filesize corresponds with the saved file on the FTP server.
    Not pretty, but it works.

  24. bill says:

    Hi,
    I got it.we can upload part by part.In this function dataChannelSocket.writeBytes()
    we can set the size and position of every part.

  25. Fredrik says:

    Bill,

    I would not buffer the transfer.
    If you do you need to make sure that the previous package is done before you send the next. As you dont get any feedback and Adobe wont lock the transfer you will need to wait X number of seconds to make sure that the transfer is done.
    But what if the transfer takes longer? -The file will be corrupt.
    So you need to set a really safe number of seconds between the chunks of data. This will make the upload very very slow! And you will always have to live with the risk that someone is sitting on a slow line and upload corrupt files over and over again.

    So send it all at once and do the checking over HTTP.

  26. bill says:

    Hi Fredrik ,
    May be you are right.But I don’t know the exact reason when I try to upload a large file the,it failed.I am going to find the reason.
    Thank you for your help.You helped me a lot.

  27. rkstar says:

    The problems with the extra-large files may be any number of things.

    Firstly, I found in the Adobe documentation that Flash Player does not “officially” support loading files larger than 100mb. I can’t quote where that is right now, but look for it under the FileReference docs.

    Second, when I was first testing uploading through FP I found that anything over 40mb (using the FileReference.upload() over HTTP) stalled and/or would crash the Flash Player.

    Uploading files is not pretty with AS currently. Hopefully Adobe will come up with a solution that will allow you to specify HTTP or FTP with the FileReference.upload func in a future version of the player. They will also need to support larger files because of all the HD video going on these days.

  28. bill says:

    The reason I am failed seems that the function FileReference.load() used up all the memory of my computer…
    I checked the adobe help document and found thate this function would load all the file into the memory…
    So,the upload failed..

  29. jp says:

    Hi rkstar,
    I tried testing with Telnet to upload a file. Until STOR filename.txt everything works.
    But I am not able to write any text to this file. Thus a text file with 0bytes is being created on the ftp server.
    The only differences in messages I get -
    PASV
    503 Entering passive mode (74,…).
    then
    following your steps-
    “At this point, you’ll have to open a new telnet session at mydomain.com
    Your FIRST telnet session will show:
    “150: data connection opened for somenewfile.txt””
    I opened a new session but doesn’t display above msg.
    In the same window I keep typing some text and then ctrl+] to escape and the file on the server is still empty.

    Another issue with the flex code is I realised the code is not able to connect to the server itself.
    When I give Alert.show(s.connected.toString()) in the connect function it gives me false. By which I am assuming the problem lies at the first step of connecting to the server.

    Any help pls!

    Thank a ton!

  30. rkstar says:

    ok, the second (data) connection that you open is where you’ll be entering data. after every \n (or \r\n) the data is written to the open file.

    the data connection must be initialized by the STOR command. after the STOR command, open the data connection and write the data. after you have closed the data connection, you will get the 150 message saying your file was written.

    in the screenshot here, you can see how i used telnet to simulate what is actually going on. in your first connection (left) do everything down to and including the STOR command. then open your data connection to the appropriate port and begin typing.

    after you close the data connection you’ll get the 150 message.

    you can either cat the file you’re writing after you close your connections, or you can tail -f it while you’re writing data so that you can see it as it happens.

    http://grab.by/TCt

  31. jp says:

    Hi rkstar,
    Thanks for your time.
    Following is the error – Could not open connection to the host, on port 23: Connect failed.
    port 23 the default port for Telnet but the ftp server’s port is 21 right?
    So I guess do I need to “Configure the TCP Port Number Used by Telnet Server”
    to 21.
    Correct me if I am leading to a wrong direction.
    Screenshots – http://www-personal.umich.edu/~jpailla/telnet_error.jpg

    -jp

  32. rkstar says:

    i don’t know why you’re trying to connect to port 23…
    your initial (command) connection is to port 21. when you give it the PASV command, you see the comma separated numbers inside parentheses. the first 4 numbers are the ip address you’re connected to and the last 2 are how you determine the port number for your data connection.

    the port number for your data connection is:
    (second last number * 256) + last number

    in your screenshots, the port would be:
    (24 * 256) + 3 = 6147

    that means that your second (data) connection should be:
    telnet 6147

    then you can write data as i’ve described above. check my screenshot again to see the flow and check the math i did to get the data port number.

  33. rkstar says:

    sorry… above should not be “telnet 6147″ but “telnet <yourserver> 6147″

  34. jp says:

    Hello rkstar,
    here is the sequence of my commands which I followed from yours –
    http://www-personal.umich.edu/~jpailla/telnet_cmd_sequence.jpg.

    I’ve tried on another computer but get the same error and I must be missing something to get the same error again and again.
    Can I send you my flex code for the server to test on your server? I know its the same as above but want to know what I am doing wrong.
    I really appreciate your time.
    Sorry to bug you but I’ve been working on this really looong.
    Thnx,
    jp

  35. gude says:

    Hi,

    I also have a trouble while uploading big files. I supposed that the limit is 131761 bytes because they are all truncated to this number of bytes.
    Please if you have a solution, let us know.

    thanks

  36. gude says:

    Hi,

    did you manage to solve the issue with big files which were truncated?

    thanks

  37. Sami says:

    I have the same problem as Michael, I think he found how to fix it but I don’t understand his message :

    Turns out FileReference.data and FileReference.load() are FP10 only so targeting 10 fixed everything. Thanks for the awesome example.

    Can some one please explain me what is he saying ?

    Thanks

  38. Sami says:

    It’s ok, he’s talking about Flash Player, you should install v10.
    When I run the app (in firefox3) every thing goes ok, but when i click on “Upload” button I have :

    150 Connection accepted

    And nothing else : there is a new file in the ftp folder but with size = 0 !!
    I’m using FileZilla Server (v 0.9.33) for windows (xp sp2), in the console I can see the user is sending a file but it seems to be stuck !!

    After several minutes I have this message :

    426 Connection timed out, aborting transfer

    What wrong ? Should I test with another FTP server ??

  39. John laPlante says:

    Samji, I had this problem for a while. The code includes a method named createRemotFile which creates the file on the remote FTP server. That is working for you. It also has a method named sendData which is responsible for sending the contents. I found that my code wasn’t instantiating the dataChannelSocket and so wouldn’t send the data. If you use the debug version of the flash player, you will get error 1009.

    If you look at Sofer’s pasted code, he moved the instantiation of the data socket to the switch statement, code 227.

    Softer put the command to set passive mode in the switch, code 200. I find that I don’t get that code in a ftpReponse, so I moved the setting of passive to 230 where the user has just logged in.

    While playing with this, I find that if I reload the webpage that contains the SWF, I get a ftpResponse that contains both 331 (pass rqd) and 230 (user logged in) in a single message. This is problematic because the switch statement is predicated on having the code at the beginning of ftpResponse. I created a hack to solve this by checking for 230 after charater 20 and if so I set the passive mode. I’m sure that could break but it works for the moment.

  40. John laPlante says:

    I’ve also had trouble uploading big files. I’ll dig into folks’ comments. I get code 450 which means “Requested file action not taken. File unavailable (e.g., file busy).” I can upload a 6 mb PFD but if I try a 12 mb file, it fails on me.

  41. deepak chajlan says:

    this cod is not working on online but work on local can any one help me out

    localy i can connect the server and upload the file but why not online

    i also upload crossdomain xml file can any one tell the step by step method to to run this code online
    plzzzzzzzzzzzzzzzzzzzzzzzzz

  42. John laPlante says:

    Deepak, you need to deliver the domain file through a socket server. It won’t work through a HTTP connection. There are some articles on the web about how to set one up.

  43. Vala says:

    Hi, for those who are interested in uploading files through FTP sockets, you’ll want to know that in this code, the dataChannelSocket won’t trigger any event while uploading neither when it finishes writing on the server. You’ll need to create a separate connection to the same FTP port, and check the size of the file you’re uploading making a function using sendCommand(“SIZE “+fileName) within a Timer. This worked just perfect for me, and this way I could make a ProgressBar and trigger a COMPLETE event when the size returned by the SIZE command is the same as the fileReference’s loaded file. You’ll need to parse the return value a bit like it’s done in the above code.

    Hope this can be handful.

    Regards,

    Vala

  44. saj says:

    I tried this and after the swf is loaded it gives 331 Password required for “myuser”. Can anyone let me know as to why this happens?I am sure the user and password I am giving is correct.

    • Janes says:

      331 User name okay, need password.

      But you said your user name and password were correct.
      hmmm, is there any special config on your ftp server?

    • Keith says:

      I ran into this too. The password command isn’t being accepted because ftp hasn’t finished processing the username. In the receiveReply function add:

      case “331″ : //User name okay, need password
      this.passWord(pass);
      break;

      This will send the password after ftp has accepted the username.

      • saj says:

        Thanks Keith,

        It worked for me. Now I am trying to do things one by one and things are fine. I changed to

        case “220″ :
        //FTP Server ready responce
        break;
        case “331″ :
        //User name okay, need password
        this.passWord(pass);
        break;
        case “230″:
        //User logged in
        this.changeDirectory(“/myDirectory/”);
        break;
        case “250″ :
        //CWD command successful
        s.writeUTFBytes(“PASV\n”);
        s.flush();
        break;
        case “227″ :
        //Entering Passive Mode (h1,h2,h3,h4,p1,p2).
        break;
        case “226″ :
        break;

  45. saj says:

    Hi,

    After the transfer is complete I want to inform the user that the transfer is complete and also close the ftp connection. Can I know how to achieve it. I tried with response 226 for transfer complete but I never got it. I checked with my ftp location and the files are getting transferred without any problem.

  46. rkstar says:

    the command socket won’t get the completed response until the data socket is closed. i struggled with this for a long time and ended up writing a daemon on the server that would listen on yet another port for a PID. the PID is of the data connection and my daemon would kill it prompting the 226 response from the command socket.

    the Socket.CLOSED event is never fired.

    • saj says:

      Hi rkstar,

      What do you mean by writting a daemon on the server that would listen on another port for a PID? Can you please explain?

  47. saj says:

    Hi,

    I need to do ftp to different ftp locations of the users. It worked fine from my local machine. But when I deployed it on my server it gave SecurityError–>Error #2048: Security sandbox violation: http://myServer.com/header.swf cannot load data from myuserftp.com:21.

    I kept crossdomain.xml in server root directory and its accessible with http://myServer.com/crossdomain.xml but still the security error is thrown.

    Do I need to anything else on flex side like loading the crossdomain.xml on application init etc.Any ideas?

  48. shelly says:

    SecurityError–>Error #2048
    Error—>Error #2031

  49. Sebi says:

    Nice piece, thank you – using it but having one addition:

    If you want to send BINARY data, e.g. an image
    you should do

    // Tell FTP to go to BINARY mode
    sendCommand(“TYPE I”);
    // before you call sendData()

    In other forums many people seem to wonder about sending binary data over flex socket
    and there are strange solutions around. However this (plus the one line above) worked for me.
    P.S.: Sofer posted it before, but it is hidden in lots of code.

  50. h_m_m_7 says:

    If you want to know when the transfer is done (or follow the percentage of your upload), you can also do that :
    1 – open a second command socket on your server whit the ProgressEvent.SOCKET_DATA
    2 – add an listener on the a ProgressEvent.SOCKET_DATA event on this socket
    2 – whit a timer, call each second on this socket the command “SIZE” + nameOfTheFileYouAreUploading when you begin upload

    You can then control your upload.
    Very simple and it works perfectly.

Leave a Reply