User Guide
Example: Uploading and downloading files 415
Beginning a file upload
The file upload is initiated when the user clicks on the Upload button on the Stage, which
invokes the
FileUpload.startUpload() method. This method calls the browse() method
of the FileReference class which causes the operating system to display a system dialog box
prompting the user to select a file to upload to the remote server. The following excerpt shows
the code for the
startUpload() method:
public function startUpload():void
{
fr.browse();
}
Once the user selects a file to upload, the select event (Event.SELECT) is dispatched,
causing the
selectHandler() method to be invoked. The selectHandler() method creates
a new URLRequest object and sets the
URLRequest.url property to the value of the
UPLOAD_URL constant defined earlier in the code. Finally, the FileReference object uploads the
selected file to the specified server-side script. The code for the
selectHandler() method is
as follows:
private function selectHandler(event:Event):void
{
var request:URLRequest = new URLRequest();
request.url = UPLOAD_URL;
fr.upload(request);
}
The remaining code in the FileUpload class is the same as the code defined in the
FileDownload class. If a user wishes to terminate the upload at any point, they can click the
Cancel button, which sets the label on the progress bar and stops the file transfer immediately.
The progress bar gets updated whenever the
progress event (ProgressEvent.PROGRESS) is
dispatched. Similarly, once the upload has completed, the progress bar is updated to notify the
user that the file has uploaded successfully. The Cancel button is then disabled until the user
begins a new file transfer.