Search Flex Components Free

Custom Search

December 29, 2007

Flash 8 File Upload Download

As we know the Flex Upload is actually use the Flash 8 FileReference object to do the work. The guy who is writing the book ‘Flash 8 Upgrade Essentials’ provided a very detail demo showing how the upload is done within Flash 8. It gives you a good insight on what’s under the hood of Flex file handling.

Example: Uploading and downloading files
The FileIO example demonstrates techniques for perform file downloading and uploading in Flash Player. These techniques are:
Downloading files to a user's computer
Uploading files from a user's computer to a server
Cancelling a download in progress
Cancelling an upload in progress
The FileIO application files are found in the Samples/FileIO folder. The application consists of the following files:
File
Description
FileIO.mxml
The main application file consisting of the MXML user interface.
com/example/programmingas3/fileio/FileDownload.as
A class that includes methods for downloading files from a server.
com/example/programmingas3/fileio/FileUpload.as
A class that includes methods for uploading files to a server.

FileIO application overview

The File IO application contains the user interface that allows a user to upload or download files using Flash Player. The application first defines a couple of custom components, FileUpload and FileDownload, which can be found in the com.example.programmingas3.fileio package. Once each custom component dispatches its contentComplete event, the component's init() method is called and passes references to a ProgressBar and Button component instance, which allow users to see the file's upload or download progress or cancel the file transfer in progress.

The relevant code from the FileIO.mxml file is as follows:

<example:FileUpload id="fileUpload" creationComplete="fileUpload.init(uploadProgress, cancelUpload);" /> <example:FileDownload id="fileDownload" creationComplete="fileDownload.init(downloadProgress, cancelDownload);" />

The following code shows the Upload File panel, which contains a progress bar, and two buttons. The first button, startUpload , calls the FileUpload.startUpload() method, which calls the FileReference.browse() method. The following excerpt shows the code for the Upload File panel:

<mx:Panel title="Upload File" paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10"> <mx:ProgressBar id="uploadProgress" label="" mode="manual" /> <mx:ControlBar horizontalAlign="right"> <mx:Button id="startUpload" label="Upload..." click="fileUpload.startUpload();" /> <mx:Button id="cancelUpload" label="Cancel" click="fileUpload.cancelUpload();" enabled="false" /> </mx:ControlBar> </mx:Panel>

This code places a ProgressBar component instance and two Button component button instances on the Stage. When the user clicks the Upload button ( startUpload) , an operating system dialog box is launched that allows the user to select a file to upload to a remote server. The other button, cancelUpload , is disabled by default, although when a user begins a file upload, the button becomes enabled and allows the user to abort the file transfer at any time.

The code for the Download File panel is as follows:

<mx:Panel title="Download File" paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10"> <mx:ProgressBar id="downloadProgress" label="" mode="manual" /> <mx:ControlBar horizontalAlign="right"> <mx:Button id="startDownload" label="Download..." click="fileDownload.startDownload();" /> <mx:Button id="cancelDownload" label="Cancel" click="fileDownload.cancelDownload();" enabled="false" /> </mx:ControlBar> </mx:Panel>

This code is very similar to the file upload code. When the user clicks the Download button, ( startDownload ), the FileDownload.startDownload() method is called, which begins downloading the file specified in the FileDownload.DOWNLOAD_URL variable. As the file downloads, the progress bar updates, showing what percentage of the file has downloaded. The user can cancel the download at any point by clicking the cancelDownload button, which immediately stops the file download in progress.

Downloading files from a remote server

Downloading of files from a remote server is handled by the flash.net.FileReference class and the custom com.example.programmingas3.fileio.FileDownload class. When the user clicks the Download button, Flash Player begins to download the file specified in the FileDownload class's DOWNLOAD_URL variable.

The FileDownload class begins by defining four variables within the com.example.programmingas3.fileio package, the following code shows:

/** * Hard-code the URL of file to download to user's computer. */ private const DOWNLOAD_URL:String = "http://www.yourdomain.com/file_to_download.zip"; /** * Create a FileReference instance to handle the file download. */ private var fr:FileReference; /** * Define reference to the download ProgressBar component. */ private var pb:ProgressBar; /** * Define reference to the "Cancel" button which will immediately stop * the current download in progress. */ private var btn:Button;

The first variable, DOWNLOAD_URL , contains the path to the file, which gets downloaded onto the user's computer when the user clicks the Download button in the main application file.

The second variable, fr , is a FileReference object that gets initialized within the FileDownload.init() method and will handle the downloading of the remote file to the user's computer.

The last two variables, pb and btn , contain references to ProgressBar and Button component instances on the Stage, which get initialized by the FileDownload.init() method.

Initializing the FileDownload component

The FileDownload component is initialized by calling the init() method in the FileDownload class. This method takes two parameters, pb and btn , which are ProgressBar and Button component instances, respectively.

The code for the init() method is as follows:

/** * Set references to the components, and add listeners for the OPEN, * PROGRESS, and COMPLETE events. */ public function init(pb:ProgressBar, btn:Button):void { /* Set up the references to the progress bar and cancel button, which are passed from the calling script. */ this.pb = pb; this.btn = btn; fr = new FileReference(); fr.addEventListener(Event.OPEN, openHandler); fr.addEventListener(ProgressEvent.PROGRESS, progressHandler); fr.addEventListener(Event.COMPLETE, completeHandler); }

Beginning the file download

When the user clicks the Download Button component instance on the Stage, the startDownload() method is to initiate the file download process. The following excerpt shows the startDownload() method:

/** * Begin downloading the file specified in the DOWNLOAD_URL constant. */ public function startDownload():void { var request:URLRequest = new URLRequest(); request.url = DOWNLOAD_URL; fr.download(request); }

First, the startDownload() method creates a new URLRequest object, and sets the target URL to the value specified by the DOWNLOAD_URL variable. Next, the FileReference.download() method is called, and the newly created URLRequest object is passed as a parameter. This causes the operating system to display a dialog box on the user's computer prompting them to select a location to save the requested document. Once the user selects a location, the open event ( Event.OPEN ) is dispatched and the openHandler() method is invoked.

The openHandler() method sets the text format for the ProgressBar component's label property, and enables the Cancel button, which allows the user to immediately stop the download in progress. The openHandler() method is as follows:

/** * When the OPEN event has dispatched, change the progress bar's label * and enable the "Cancel" button, which allows the user to abort the * download operation. */ private function openHandler(event:Event):void { pb.label = "DOWNLOADING %3%%"; btn.enabled = true; }

Monitoring a file's download progress

As a file downloads from a remote server to the user's computer, the progress event ( ProgressEvent.PROGRESS ) is dispatched at regular intervals. Whenever the progress event is dispatched, the progressHandler() method is invoked and the ProgressBar component instance on the Stage is updated. The code for the progressHandler() method is as follows:

/** * While the file is downloading, update the progress bar's status. */ private function progressHandler(event:ProgressEvent):void { pb.setProgress(event.bytesLoaded, event.bytesTotal); }

The progress event contains two properties, bytesLoaded and bytesTotal , which are used to update the ProgressBar component on the Stage. This gives the user a sense of how much of the file has already finished downloading and how much remains. The user can abort the file transfer at any time by clicking the Cancel button below the progress bar.

If the file is downloaded successfully, the complete event ( Event.COMPLETE ) invokes the completeHandler() method, which notifies the user that the file has completed downloading and disables the Cancel button. The code for the completeHandler() method is as follows:

/** * Once the download has completed, change the progress bar's label one * last time and disable the "Cancel" button since the download is * already completed. */ private function completeHandler(event:Event):void { pb.label = "DOWNLOAD COMPLETE"; btn.enabled = false; }

Cancelling a file download

A user can abort a file transfer and stop any further bytes from being downloaded at any time by clicking the Cancel button on the Stage. The following excerpt shows the code for cancelling a download:

/** * Cancel the current file download. */ public function cancelDownload():void { fr.cancel(); pb.label = "DOWNLOAD CANCELLED"; btn.enabled = false; }

First, the code stops the file transfer immediately, preventing any further data from downloading. Next, the progress bar's label property is updated to notify the user that the download has been successfully cancelled. Finally, the Cancel button is disabled, which prevents the user from clicking the button again until they attempt to download the file again.

Uploading files to a remote server

The file upload process is very similar to the file download process. The FileUpload class declares the same four variables, as shown in the following code:

private const UPLOAD_URL:String = "http://www.yourdomain.com/your_upload_script.cfm"; private var fr:FileReference; private var pb:ProgressBar; private var btn:Button;

Unlike the FileDownload.DOWNLOAD_URL variable, the UPLOAD_URL variable contains the URL to the server-side script that will upload the file from the user's computer. The remaining three variables behave the same as their counterparts in the FileDownload class.

Initializing the FileUpload component

The FileUpload component contains an init() method, which gets called from the main application. This method takes two parameters, pb and btn , which are references to a ProgressBar and Button component instance on the Stage. Next, the init() method initializes the FileReference object defined earlier in the FileUpload class. Finally, the method assigns four event listeners to the FileReference object. The code for the init() method is as follows:

public function init(pb:ProgressBar, btn:Button):void { this.pb = pb; this.btn = btn; fr = new FileReference(); fr.addEventListener(Event.SELECT, selectHandler); fr.addEventListener(Event.OPEN, openHandler); fr.addEventListener(ProgressEvent.PROGRESS, progressHandler); fr.addEventListener(Event.COMPLETE, completeHandler); }

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.

Related Flex Tutorials