Flex makes the job of selecting single or multiple files easy. Our aim here is to allow the user to click on the "Select Files" button and then select the files to upload. Once the files are selected, the user can then use the "Start Upload" button to post the files to the server. Let's start by getting the files from the user. We will be using the FileReferenceList class to accomplish this task. Alternatively, if we only wanted to upload a single file, we would use the FileReference class. The first step is importing the necessary code: // Imports import mx.events.ItemClickEvent; import flash.net.FileReferenceList; The ItemClickEvent was already added for the ButtonBar. The "import FileReferenceList" statement now gives us the ability to instantiate the object we need to retrieve the list of files from the user. The next step is declaring a FileReferenceObject to use. We'll call this object uploadList. // Properties public var uploadList:FileReferenceList; To create a new instance of this FileReferenceList, use the "new" operator like so: // create an instance of the File Reference List uploadList = new FileReferenceList(); To keep things nice and neat, I've created a method called "init" which is called once our application fires the creationComplete event. Creating an init method is good for expandability. I can now place any other initialization code in the same method. The FileRefenceList class contains a method called browse, which will open a native File Dialog box and request that the user select mutilple files. The dialog window is different for every operating system. We can trigger this dialog in our buttonHandler method. We already have a case for "Select Files" which will call 'uploadList.browse()'. The browse method takes over from this point. I'm developing with Microsoft Vista, which has the following look: Specifying File Types We can call the browse method as we did above with no parameters. This tells the native file selection dialog to allow the user to select any files they wish. This may be good in some cases, but there are times where we want only certain file types to be allowed. To remedy this, the browse method takes a parameter that limits the file types which can be selected. The parameter is an array that contains FileFilter Objects. Here is how we would use this: // create a fileFilter - class declaration private var imageTypes:FileFilter; // set the file filter type - jpg/png/gif - init method imageTypes = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
// upload - buttonHandler uploadList.browse([imageTypes]);
For simplicity, I placed these lines of code in sequence. As you will see from the final code below, they actually exist in different places. Note here that I'm using the short form of an array []. Calling browse and passing our array of fileFilters effectively removes all non jpg, png, and gif files from the file list.
blog comments powered by Disqus |
|
|
|
|
|
|
|