Downloading a folder from a FTP server with AS3

In a time like this when semester one of uni is a month away and it’s too hot to go to the gym, then continue working on some coding seems like a nice idea. A week or two ago, thanks to Sathesh, I learnt how to use Socket to download a file from a FTP server. Now a need to download an entire folder has arisen. That or learn ByteArray to decompress a GZip file. I chose to go with the former. May this be an explanation post to myself later on.

I have found that to download a folder, you would need to get a list of file names in the folder, store it into an array or similar and use a download function to download it one-by-one. I also found that Flash can handle downloading multiple files at the same time but I’ve only tried doing that once and with my internet quota capped at the moment. Multiple files downloading may not seem to be a good idea.

Based on the FTP Downloader class from the earlier post, I added a function to get a list of all names. Since the LIST command in FTP returns everything to know about the file: permissions, date, time, file size, etc, I used a regular expression to fix the problem. With, I’ve found /(\.|\w)+$/gm works well and able to get only the file names of the files.

This is the ls function to list all the file names of the folder:

public function ls(remoteFolder:String = null, stringToProcess:String = null):void
   _filesList = new Array();

   if(remoteFolder != null)
      // start getting a string of the list of files in a folder
      _process = "getDirList";
      _remoteFolder = remoteFolder;
   else if(stringToProcess != null)
   var str_arr:Array = stringToProcess.match(_nameRegex);
   if(str_arr != null)
      _filesList = str_arr;
      dispatchEvent(new Event(LIST_AVAILABLE));

How it works is that firstly, the coder calls ls() and only fills in the remoteFolder parameter, leaving the latter null. The function will then connect to the data port and it will handle listing and returning to the string, which will leave remoteFolder parameter null and fill in stringToProcess. This will applies the regex and dispatch an event to notify the main program that the list is available to grab. _filesList is a private variable with a getter function.

Once the list is grabbed and stored into an array, the easy part comes along. Now using the function downloadFile() from the earlier post, one can download the files individually.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s