Previous Page
Next Page

Recipe 23.2. Detecting When a User Selects a File to Upload

Problem

You want to detect when a user selects a file in order to start a download.

Solution

Listen for the select event. Listen for the cancel event to detect when the user has clicked the cancel button.

Discussion

The download( ) method does not pause the execution of ActionScript code. As soon as the download( ) method is called, Flash Player attempts to open the save dialog box. Once it either successfully opens the save dialog box or throws an error, the Flash Player continues to the next line of ActionScript code. That means you cannot expect the user to have selected a file and clicked the Save button immediately following the download( ) method call. Rather, you must listen for a select event to tell you when the user has pressed the Save button. The select event is of type Event, and you can use the Event.SELECT constant to add the listener, as follows:

fileReference.addEventListener(Event.SELECT, onSelectFile);

As soon as the select event occurs, you can retrieve the filename the user has selected by reading the name property of the FileReference object:

private function onSelectFile(event:Event):void {
    trace(event.target.name);
}

The user also has the option of clicking the Cancel button from the save dialog box. If the user clicks the Cancel button, the file is not downloaded, and the dialog closes. When the user clicks the Cancel button, the FileReference object dispatches a cancel event of type Event. You can use the Event.CANCEL constant to add a listener, as follows:

fileReference.addEventListener(Event.CANCEL, onCancelDialog);

See Also

Recipe 23.1


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)