Archive for the ‘Flex’ Category

Flex: Multiple File Uploader

October 1st, 2009 13 comments

Flex Multi UploaderUploading is such a common task and can often be a little painful so I decided to write a small library in Flex which simplifies the task. I have released it under GPL license so feel free to use and modify it according to the conditions :)

The Flex client side uploader supports multiple file upload with queuing and multiple threads, meaning more than one upload can be active at a time. It is also written in component style so creating an instance of the uploader is very simple and can be achieved in only a few lines of code (see the example below). It also supports posted additional data with the file upload, handy if you need to pass instructions to the back-end upload script.

The back-end script is not included in the library but could easily be implemented in any language. I have however supplied a PHP example below of how to implement the back-end script to support the Flex uploader (see the example below).

One final note, this code is not polished, it’s definitely Alpha…but still very usable. If you have any issues or questions please let me know, cheers.

Simple example implementation of uploader library

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=""
			private function init():void{
	<cc:FileUploadComp id="fileUploader"

PHP backend example implementation of uploader code

	$tmpFileName = isset($_FILES['Filedata']['tmp_name']) ? $_FILES['Filedata']['tmp_name'] : '';
	$orgFileName = isset($_FILES['Filedata']['name']) ? $_FILES['Filedata']['name'] : '';
	$mydata = isset($_REQUEST['mydata']) ? $_REQUEST['mydata'] : '';
	error_log('tmpfile: ' . $tmpFileName);
	error_log('filename: ' . $orgFileName);
	error_log('mydata: ' . $mydata);	

	if (true){
		print 'ok'; 
		header('Status: 500 ' . $resultAry[1]);
		header('HTTP/1.1 500 ' . $resultAry[1]);
		$outputStr = '<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">' .
				 '<html><head>' .
				 '<title>500 ' . $resultAry[1] . '</title>' .
				 '</head><body>' .
				 '<h1>500 ' . $resultAry[1] . '</h1>' . 
				 '<hr>' .
		print $outputStr;

Also here’s and example of a Flash crossdomain.xml (this one is reasonably open!) which will be needed in the root of your site…otherwise flex will complain.

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "">
	<allow-access-from domain="*" to-ports="*"/>
	<site-control permitted-cross-domain-policies="all"/>

Demo Flex Uploader

DOWNLOAD (version 1.0a)

Flex: View Source Code

August 21st, 2009 No comments

If you want to publish your application source code by right-clicking on the application SWF and you’re using FlexBuilder then from the top menu bar select:

  • File->Export->Release Build
  • Right click you project folder and select “Export”

Alternatively if you want to format the source code your self then you can set the “viewSourceURL” attribute in the Application tag which should enable the “View Source” option on the right-click menu. And of course when you click “View Source” you should be navigated to the value of “viewSourceURL”.

For more information:

Flex: High Definition MP4 with Flex VideoDisplay

August 21st, 2009 No comments

HD Firstly I just like to say it’s not really true “High Definition” but rather “Higher Definition”. However if you are are looking to improve playback via the Flex VideoDisplay component then make sure you encode your mp4 (which is in fact not really an mp4) using the H264 codec, sometimes referred to as AVC or AVC1. It’s not really a big issue as there are plenty of free H264 encoders around, like

You ‘ll soon know if the mp4 is encoded correctly as you’ll probably get a black square box with no video and only audio if the mp4 is not compatible.

Flex: ExternalInterface – The Flex Javascript Bridge

August 21st, 2009 No comments

It is really very easy to gain access to Javascript via Flex, the Javascript API is made available via flash.external.ExternalInterface flex class. There are a couple of methods you can use, you can either:

  • Make calls to pre-existing functions (yours or exists JS ones) using the flex function where the argument to call is a string which represents the normal Javascript function invocation.
  • Defined a whole Javascript function inside Flex as a string and pass that string to call, will then automatically execute the function.

There is of course no real use in passing in arguments if you are pre-defining the Javascript function as a string because you can just use those value during the generation of the string.

Below is an example of creating and fetching a Javascript cookie, you never know it might come in handy :)

// ************************ START EXAMPLE *****************************

 * Flex class ExternalInterface does all the magic

import flash.external.ExternalInterface;

public function createCookie(name:String,value:String,days:int=0):void{

    var js:String = "function createCookie(){" +
                     "var expires = '';" +

    "if (" + days + " > 0){" +
        "var date = new Date();" +
        "date.setTime(date.getTime()+(" + days + "*24*60*60*1000));" +
        "expires = 'expires = ' + date.toGMTString();" +
        "}" +
        "document.cookie = '" + name + "=" + value + "; expires=' + expires + '; path=/';" +


public function getCookie(cookieName:String):String {

   var r:String = "";

    var search:String = cookieName + "=";
    var js:String = "function getCookie(){return document.cookie;}";
    var cookieVariable:String =;

    if (cookieVariable.length > 0) {
        var offset:int = cookieVariable.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            var end:int = cookieVariable.indexOf(";", offset);
            if (end == -1){
                end = cookieVariable.length;
            r = unescape(cookieVariable.substring(offset, end));

    return r;


// ************************ END EXAMPLE *****************************

Flex: Google Analytics Howto

August 20th, 2009 No comments

How do you track events in Google Analytics (GA)? Well it’s easy enough when your’re dealing with regular html markup web pages (I’m assuming your’ve done a basic implementation of Google Analytics before), but what about flex. Once the webpage that your main flex application sits in is loaded nothing else will be tracked by GA.

The easiest way to track any action in a Flex application using GA is to use the Flex-Javascript bridge in flash.external.ExternalInterface

Also you don’t want any possibility that Flex is going to hang around for the Javascript call to complete, and if there’s a communication issue then GA could slow down your program. So in a nunshell what is needed is an asynchronous event driven framework for GA which is implemented around Flex ExternalInterface calls to Javascript.

In order to make the below example work you will need a Google account with Analytics setup on a domain. You will need to check your supplied GA Javascript code and find your unique tracking ID, which will look something like: UA-xxxxxxx-x. You can setup and test the below code to a point in FlexBuilder but ultimately you will need to integrate your code onto your website URL which is registered with GA. The GA Javascript code will not execute unless it’s running integrated on your website (it’s most likely due to Javascript environment variables or the lake of)

You need a tool to monitor HTTP traffic from your browser, Firefox has plug-in call: Tamper Data which works well enough.

This is the core Google Analytics code which should always be listening for Flex tracking events and ultimately makes the Javascript call to track your custom event.

package Framework.Utilities.GoogleAnalytics{
	import Framework.Utilities.GoogleAnalytics.Events.TrackingEvent;
	import Framework.Utilities.JavascriptAPI;
	public class GoogleAnalytics{
		private var globalEventDispatcher:EventDispatcher = null;
		private var trackingId:String = '';
		private var javascriptApi:JavascriptAPI = null;
		public static const GANALYTICS_URI_SOAP_PREFIX:String = '/SOAP/';
		public static const GANALYTICS_URI_UI_PREFIX:String = '/UI/';
		public function GoogleAnalytics(globalEventDispatcher:EventDispatcher,trackingId:String = ''){
			this.trackingId = trackingId;
			this.globalEventDispatcher = globalEventDispatcher;
			javascriptApi = new JavascriptAPI();
		public function setTrackingId(trackingId:String):void{
			this.trackingId = trackingId;
		public function getTrackingId():String{
			return trackingId;
		private function initListeners():void{
		private function trackingHandler(te:TrackingEvent):void{
	    	var currentTrackingId:String = trackingId;
	    	if (te.getTrackingId() != null){
	    		if (te.getTrackingId() != ''){
	    			currentTrackingId = te.getTrackingId();
	    	if (currentTrackingId != null){
	    		if (currentTrackingId != ''){
	    			// Make the google analytics call via javascript


This is the tracking event which will hold your custom Google Analytics call which will be fired every time you want to track something in Flex.

package Framework.Utilities.GoogleAnalytics.Events{

	public class TrackingEvent extends Event{

	    public static const GOOGLE_TRACKING_EVENT:String = 'GOOGLE_TRACKING_EVENT';
	    public var urlOrUrl:String = '';
	    private var trackingId:String = '';
	    public function TrackingEvent(urlOrUrl:String,type:String = GOOGLE_TRACKING_EVENT):void{
	    	this.urlOrUrl = urlOrUrl;
	    public function setTrackingId(trackingId:String):void{
	    	this.trackingId = trackingId;
	    public function getTrackingId():String{
	    	return trackingId;
		public override function clone():Event{
			var trackingEvent:TrackingEvent = new TrackingEvent(urlOrUrl,type);
	    	return trackingEvent;

This is a small class which uses the Flex ExternalInterface call to execute Google Analytics Javascript, which in turn makes an HTTP call to the GA server.

package Framework.Utilities{
	import flash.external.ExternalInterface;
	public class JavascriptAPI{
		public static const PLUGIN_MODE:int = 0;
		public static const AIR_MODE:int = 1;
		public static const GANALYTICS_URI_SOAP_PREFIX:String = '/SOAP/';
		private var mode:int = 0;
		public function JavascriptAPI(mode:int = 0){
			this.mode = mode;
		public function googleTracker(trackerId:String,action:String):void{
			if (mode == PLUGIN_MODE){
				var js:String = "function googleTracker(){" + 
								"var pageTracker = _gat._getTracker('" + trackerId + "');"+
								"pageTracker._trackPageview('" + action + "');}";;

This is how you use the above code

 * Where myEventDispatcher extends an EventDispatcher

var googleAnalytics:GoogleAnalytics = new GoogleAnalytics(myEventDispatcher);

 * Then somewhere else in your application do this
 * to track your something in Google Analytics 

var googleTrackingEvent:TrackingEvent = new TrackingEvent('myTrackingStringOrUrl');