Extract files in AS3 (AIR)

Oct. 16, 2008 2 Comments Posted under: AIR, Development, Flex

I am currently working on a client side application written in AIR. I need to allow the user to drag a list of files onto the application and then validate them checking for file type and size.

I hit a problem with the user dragging folders, as they are handled as a file with a property of directory. In order to iterate through an array of these files and folders I needed a way to turn an array of files and folders into an array of just the files.

In the following function you can pass it an array of files and it will flatten it, but returning an array of just the files. It also removes hidden files!

		/**
		 * This function takes an array of files and folders and retuns an array of just files
		 * This function also removes hidden files
		 * @param files
		 * 
		 */		
		private function _cleanFileArray( files : Array ):Array
		{
			var arrayToReturn : Array = new Array();
 
			for each ( var fileOrDir : File in files )
			{
				if( fileOrDir.isDirectory )
				{
					// If we find a directory, call this method again to extract the files
					// This will recurse until there are only files in the returning array
					var subArray : Array =  this._cleanFileArray( fileOrDir.getDirectoryListing() );
					arrayToReturn = arrayToReturn.concat( subArray ); // Combin the files with the arrayToReturn
				}else if( fileOrDir.isHidden ){
					// Skip hidden files
				}else{
					// If we have a file add it to the array of files to return
					arrayToReturn.push( fileOrDir );
				}
			}
			return arrayToReturn;
		}

You could turn this into a static function on a helper class if you want. Tags: Removing folders from file list, extracting files from folders, flattening folders, removing hidden folders.

This entry was posted on Thursday, October 16th, 2008 at 4:01 pm and is filed under AIR, Development, Flex. You can leave a comment and follow any responses to this entry through the RSS 2.0 feed.

2 Comments Leave a comment

  1. starpause 23 February 2009 at 10:18 pm #

    Clean utility function, thanks!

  2. Karl Freeman 23 March 2009 at 10:40 pm #

    Fantastic function here, Thanks a bunch!

Leave a Reply