views:

157

answers:

2

Hello,

I am uploading files using the upload() method of the FileReference class. I want to display the current connection speed and I was wondering what was a good way to do that.

My current technique is to use a Timer every 1 mili second such as follows:

var speed:Function = function(event:TimerEvent):void {
    speed = Math.round((currentBytes - lastBytes) / 1024);
    lastBytes = currentBytes;
}
var speedTimer:Timer = new Timer(1000);
speedTimer.addEventListener(TimerEvent.TIMER, uploadSpeed);

and currentBytes gets set into the ProgressEvent.PROGRESS. This technique seems imprecise. I was wondering what other ways I could use to calculate the upload speed while uploading and display it in real time.

Any ideas or opinions are welcomed!

Thank you very much,

Rudy

A: 

You can moniter the upload speed on the server and then send that data back to the client. This technique is often used for ajax file upload forms.

Maz
Okay thank you. If I had to use only the client, is there any good method for the client side please?
Rudy
A: 

If that code block is a copy and paste it certainly won't work as you have expected it to. You declare speed as a function within which you appear to redefine it as a number. I appreciate the Flash IDE let's you get away with sketchy grammar, but code like that is going to lead you into all kinds of trouble. Try to be explicit when writing your code.

Try something like this, replacing yourLoader with whatever identifier you assigned to the uploader:

private var speed:Number = 0;
private var lastBytes:uint = 0;

private function uploadSpeed(event:TimerEvent):void
{
   speed = Math.round((yourLoader.currentBytes - lastBytes) / 1024);
   lastBytes = yourLoader.currentBytes;
}

private var speedTimer:Timer = new Timer(1000);
speedTimer.addEventListener(TimerEvent.TIMER, uploadSpeed);

That should calculate how many bytes moved in 1 second intervals.

Edit:

You might like to make the interval a little smaller than 1000ms and calculate an average speed for your last n samples. That would make the number your users see appear more stable than it probably does right now. Make speed an Array and .push() the latest sample. Use .shift() to drop the oldest samples so that you don't lose too much accuracy. Trial and error will give you a better idea of how many samples to hold and how often to take them.

Ben
That was not a line per line copy and paste, I tried to rewrite it quickly here and set the name "speed" twice. It's not the case in my program, but good catch, thank you.I like the idea of an Array and pushing the elements and just calculating an average out of n samples. It will make it more stable (although sudden drops or speed increase will take some time to reflect), but it is still a better solution. Thank you!
Rudy