Wednesday, August 4, 2010

Working with files in Actionscript 3: Part 3

In this tutorial we will learn about the download progress of a FileReference object.

When a part of file is downloaded to user's computer, FileReference object creates a progress event. To create a listener for this event we use ProgressEvent.PROGRESS:

fileReference.addEventListener(ProgressEvent.PROGRESS, onProgress);

The progress event has 2 properties - bytesLoaded and bytesTotal. Using those, we can find out and display (in percents or bytes) the download progress.

Let's create a function that traces bytes that are loaded and total bytes.

function onProgress(event:ProgressEvent){
trace(event.bytesLoaded + "/" + event.bytesTotal + " bytes loaded.");
}

You will probably want to display it as a text field to the user, or create a visual progress bar. In the example below we generate a bar that shows how much of the file has been downloaded:

var barwidth:Number=100
var barheight:Number=10

function onProgress(event:ProgressEvent){
graphics.clear();
graphics.beginFill(0xCCCCCC);
graphics.drawRect(20,20, barwidth, barheight);
graphics.endFill();

graphics.beginFill(0x00CCFF);
graphics.drawRect(20,20, barwidth * event.bytesLoaded / event.bytesTotal, barheight);
graphics.endFill();
}

When the download completes, FileReference object gives out a complete event. To create a listener for this event we use Event.COMPLETE:

fileReference.addEventListener(Event.COMPLETE, onComplete);

function onComplete(Event){
trace("File finished downloading!");
}

Thank you 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 4
Working with files in Actionscript 3: Part 5

No comments:

Post a Comment