Thursday, August 5, 2010

Working with files in Actionscript 3: Part 4

Today we will learn how to open a browse dialog window that allows our user to choose a file (or files).

Method browse() of FileReference or FileReferenceList objects will open a dialog window, where you can browse your local discs and select files.

What's the difference between FileReference and FileReferenceList you say? Well it is that FileReference allows the user to choose one file, while FileReferenceList - multiple files (holding control or shift on PC, command on Mac).

fileReference.browse();

Just like the download() method, browse() can give errors, and it is best to handle these errors using try...catch. IllegalOperationError can occur if there already is a dialog window open (only one window can be active at the same time!) and if the user disabled file browsing in his Flash Player settings.

So what do we do?

try {
fileReference.browse();
}
catch (illegalOperation:IllegalOperationError){
// your error handling code here
}

If we do not handle errors, Flash Player will give out a standart error message, that might confuse the user.

What do we do if we only want to allow user to see specific file formats in his dialog window? Because, by default, all formats are shown and allowed to pass through. We can filter formats using flash.net.FileFilter array. FileFilter has 2 necessary parameters: the first one is what will be shown in the "Files of type" sub-menu of the browse window, the second parameter shows what file formats are allowed.

var myFilter:FileFilter = new FileFilter("Images", "*.gif; *.png; *.jpg");

To pass this filter to our FileReference object, do it when you call the browse() method:

fileReference.browse([myFilter]);



You can also create more than one filters (Images, Documents, All, etc), pass them like this:

fileReference.browse([myFilter1, myFilter2, myFilter3]);

Thanks for reading!

Related:

Working with files in Actionscript 3: Part 1
Working with files in Actionscript 3: Part 2
Working with files in Actionscript 3: Part 3
Working with files in Actionscript 3: Part 5

No comments:

Post a Comment