ActionScript 3.0 - Display Object Primer - Part 1

:: June 25, 2007

One important change in Flash CS3 from a programming standpoint is about the usage of the MovieClip properties like attachMovie, createEmptyMovieClip et all. This was one topic in which I fumbled a bit to understand when I started with AS3 and thought would write a series of simple tutorials which will make things more clear for people starting with ActionScript 3.0 and specifically for those who use MovieClip methods a lot in their day to day work.

Some important facts to know of before we start with are:

  1. API's like attachMovie, createEmptyMovieClip, removeMovieClip, and duplicateMovieClip are either removed or replaced with new API's.
  2. Most of the MovieClip related API's are present with the flash.display.DisplayObject and flash.display.DisplayObjectContainer packages.
  3. All of the MovieClip related operations are based on a container based approach in which you have a DisplayObjectContainer and you can have DisplayObjects like MovieClips and Sprites in them.
  4. Depths are auto managed in ActionScript 3.0 and hence you need not manually specify and manage depths of the DisplayObjects yourselves but rather Flash Player does it for you.
  5. Still, if you want to have greater control of the depth yourself, you can use a method named addChildAt() method to manually specify the level in which you want the child to be added.
  6. addChild API is the equivalent of attachMovie or createEmptyMovieClip in AS 2.0.

Now, lets get to the basics of DisplayObject programming. I will try to illustrate the concept using a simple diagram shown below:

DisplayObjectBasics

As I told before, everything in AS3 is based on a container approach. The main timeline (root) can be considered as the main container and it in-turn can contain several other containers within it. In this case we are going to create two containers within the main container and name them as "Container 1" and "Container 2".

To add the two sub containers to the main timeline, you create a container by using the code:

var container1:YellowContainer = new YellowContainer();

Note that YellowContainer is the linkage name and the class object of a yellow container movieclip which I have in the library.

Now you can specify some properties for this container, in this case it is the X and Y values:

container1.x = 200;
container1.y = 100;

Note that _x and _y is now replaced with x and y without the underscores.

To name this container (equivalent of giving an instance name to a MovieClip in AS 2.0):

container1.name = "Container 1";

Finally to add this container to the main timeline you use:

this.addChild(container1);

in this case the word "this" refers to the main timeline. The code above is equivalent to writing:

_root.attachMovie("container1");

Now we have added a container to the main timeline, the next step would be to add some elements to this container. We do this in the same way we did while creating the main container:

//Add some elements into the Container 1
var gb:GreyBall = new GreyBall();
gb.name = "Grey Ball";
// Add the grey ball to Container 1 - note that the ball gets
// attached to the registration point of the YellowContainer and not on the stage
container1.addChild(gb);

In this case, GreyBall is a MovieClip which I have in my library. Note that, at this stage the Grey Ball gets attached to the registration point of the YellowContainer and not to the stage. This is accomplished by the script:

container1.addChild(gb);

which indicates that this has to be added to the container1.

In a similar fashion you can add other elements to each of the container. The complete code which I used is here:

 

import flash.display.*;

// Create two containers and position them
var container1:YellowContainer = new YellowContainer();
container1.x = 200;
container1.y = 100;
// Give a name to the container
container1.name = "Container 1";
// Add it to the stage
this.addChild(container1);

var container2:GreenContainer = new GreenContainer();
container2.x = 275;
container2.y = 100;
container2.name = "Container 2";
this.addChild(container2);

//Add some elements into the container 1
var gb:GreyBall = new GreyBall();
gb.name = "Grey Ball";
// Add the grey ball to Container 1 - note that the ball gets
// attached to the registration point of the YellowContainer and not on the stage
container1.addChild(gb);

// Add the next ball
var rb:RedBall = new RedBall();
rb.y = 40;
rb.name = "Red Ball";
container1.addChild(rb);

//Add some elements into container 2
var grb:GreenBall = new GreenBall();
grb.name = "Green Ball";
// Add the grey ball to Container 1 - note that the ball gets
// attached to the registration point of the YellowContainer and not on the stage
container2.addChild(grb);

// Add the next ball
var bb:BlueBall = new BlueBall();
bb.y = 40;
bb.name = "Blue Ball";
container2.addChild(bb);

// Now, moving a container will move the children attached with it too
container1.y = 150;

// Getting the child elements within a container
trace(container1.getChildAt(1).name);
trace(container1.getChildAt(2).name);

As you would see from the code and as you play around with it a bit, manipulating the container affects the elements container within it too.

You can download the source code of the file which I have used in this example from here: DisplayObject.zip

** Note **

Its very important to note that in AS3 you cannot set the linkage identifier of an MovieClip like how you do in AS2. Instead, every MovieClip which can be attached is identified by a Class Name like the one shown below:

Linkage

As you can see from the above image, the identifier box is greyed out and is not available in ActionScript 3.0. When you right click on a MovieClip in your library and select the option "Export for ActionScript", Flash assigns the name of the MovieClip (without spaces) as the Class name. When you click on OK you will be prompted with a warning dialog like this:

ASClass

If you don't have (or don't want to) a class associated with the MovieClip you can click on the OK button and Flash internally would create a associated class for the MovieClip automatically. You can also specify the base class which you want your MovieClip to be associated with. The default is flash.display.MovieClip and if you want you can change this to something like flash.display.Sprite.

Doing this procedure is equivalent to creating a class with the name GreenContainer with a dummy constructor and associating it with the MovieClip as a class.

For first time users this may be very confusing and misleading. The first time I learnt it I wasted close to half hour trying to figure out how to use this and what happens internally when one does that.  

 

In the next part of the tutorial I will cover more on Sprites, DisplayObject manipulation and depth management. See you until then !

 

Timer Class - ActionScript 3.0

:: January 03, 2007

The Timer class is a new addition to AS 3.0. The Timer class is similar to the setInterval function in AS 2.0 but has some more features added to it. One of such feature is the ability to start and stop the timer when needed.

Timer in AS 3.0 behaves a little different than the setInterval call in AS 2.0. A timer fires a timer event at regular intervals (the interval which is defined when defining the timer). As with the case of setInterval one can specify the time interval in which the event has to be fired.

The Timer class is part of the flash.utils package and has to be imported before one can use it. The declaration goes like this:

import flash.utils.Timer;

As mentioned earlier a Timer has a event associcated with it which is called a TimerEvent. The TimerEvent class is present in the flash.events package and if thie TimerEvent is used, one has to import the event before using it.

import flash.events.TimerEvent;

Now for the syntax of declaring a Timer it goes like this:

var myTimer:Timer = new Timer(delay, iterations);

One primary difference between the setInterval call and using a Timer is that, the Timer has a extra parameter which says how many times the timer has to fire (iterations). If you want the timer to iterate forever then the iteration can be declared as 0. This would keep firing the Timer forever.

To listen to the timer you need to add a listener which listens to the TimerEvent.

myTimer.addEventListener(TimerEvent.TIMER, drawRectangle);

and then start the timer.

myTimer.start();

At this point its also important to note that the getTimer function in AS 2.0 still exists and is in the package flash.utils and can be used as:

flash.utils.getTimer();

Sample code:

package {
     import flash.utils.Timer;
     import flash.utils.getTimer;
     import flash.events.TimerEvent;
     import flash.display.Sprite;
    

     public class TimerExample extends Sprite
     {
          public function TimerExample()
          {
               var myTimer:Timer = new Timer(100, 10);
               myTimer.addEventListener(TimerEvent.TIMER, drawRectangle);
               myTimer.start();
           }
          private function drawRectangle(evt:TimerEvent):void
          {
                trace(flash.utils.getTimer()+ " : " + evt);
          }
      }
}

The other useful properties that are present in the Timer class are:

currentCount - Returns the total number of times the timer has fired since it started at zero.

repeatCount - Returns the total number of times the timer is set to run.

running - Returns true if the timer is running else false.

delay - Returns the delay in milliseconds and can also be set while the timer is running.

The other two methods of the Timer class which the example above doesn't cover are:

stop() - Stops the current running timer.

reset() - Resets the currently running timer and sets the current count to 0.

Another event which is associated with the TimerEvent is:

TimerEvent.TIMER_COMPLETE - This event is fired when the timer is completed and can used as:

myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, drawRectangle);

AS3 Primer : Packages

:: December 08, 2006

If you are used to coding in classes, the first notable difference you will find in AS3 is the usage of packages. Every class definition starts with the keyword "package" and then is followed by the actual class definition(s). In AS3 all classes MUST be placed inside a package such as:

package {

    public class Example {

    }

What exactly is a package?

A package is a simple way of organizing classes (of related content) into groups. It's similar to the com.xxx.yyy notation and is synonymous with directory in the file system. So, say for example I declare a package like this:

package com {

   public class Example {

   }

}

This ideally means that the class exists in the directory named com which is relative to the place where my FLA resides. The same applies to the example below:

 

package com.lah {

}

In this case the class file would exist in a subfolder named lah inside the com folder.

What is the purpose of using packages?

The simple purpose would be to better organize your classes and to avoid conflicts of classes. Say for example you have two classes with the same name which are responsible for doing two different tasks. Lets take a simple example of a login system and our application has two types of users - teachers and students. I would want to package all my teacher management related operations in a package named com.lah.teachermgmt and com.lah.studentmgmt. Considering that the login mechanism for the student and teacher is different I would have two LoginManager classes one in the package com.lah.teachermgmt and yet another in com.lah.studentmgmt. In this case, I can have two classes with the same name but under different packages.

By convention, package names are always lowercase characters as against class names which starts with a capital letter.

Usage Example:

Filename : com\lah\Example.as

package com.lah {

   public class Example{

      public function Example()

      {

           trace("Example");

       }

   }

}

Filename : Example.fla

import com.lah.*;

// for importing all the classes in the package com.lah or one can use import

// com.lah.Example; to import only a specific class in a package.

var myExample:Example = new Example(); //traces "Example"

Understanding ExternalInterface in Flash 8

:: October 26, 2005

What is ExternalInterface?

ExternalInterface (flash.external.ExternalInterface) is a set of API which lets you communicate seamlessly between ActionScript and the Flash Player container. The container can be a HTML page containing some JavaScript functions, a Visual Basic or VC++ wrapper or a 3rd party desktop application which has Flash player embedded in it. The concept is very similar to using fscommand to communicate with JavaScript but ExternalInterface is more flexible and powerful than fscommand. With ExternalInterface you can call a JavaScript function from Flash and send any number of arguments in most of the data types like Boolean, String, Numbers etc., and the JavaScript function can send data back to Flash and is received by Flash almost immediately.

For a matrix of Browser - OS support look at the table in the livedocs here.

Properties & Methods in ExternalInterface Class

Properties :

public static available : Boolean [read-only]

Usage:
var isAvailable:Boolean = ExternalInterface.available;

Methods:

public static addCallback(methodName:String, instance:Object, method:Function) : Boolean

Usage:

ExternalInterface.addCallback("flAlert", null, showAlert);

In this case flAlert is not the actual function which is written inside Flash but a friendly name which the JavaScript or the host application can call to invoke the actual function ( in this case showAlert) which is written in Flash.

**Note** : This method returns a Boolean value of true if the call was successful and false if it fails. The reason for failure may be due to a non-existent function, a security sandbox restriction or some other error. The LiveDocs page for ExternalInterface has some comments to the problem people are facing with and some answers to them.

public static call(methodName:String, [parameter1:Object]) : Object

This method is used to call a function defined in the host application.

Usage:

ExternalInterface.call("jsAlert", "Welcome");

This method returns an Object which is the response received from the host application.

To summarize addCallback method is used to communicate FROM the host application TO flash and the call method is used to communicate FROM flash TO the host communication.

You can see a simple example here.

Download the example files here.

The FLA file has extensive inline comments to understand what is going on. If you still have doubts leave a comment and I will answer.

Related readings:

ExternalInterface (flash.external.ExternalInterface)
Simplecart and External Interface (Flash 8)
External Interface example @ deconcept
JavaScript Integration in Flash 8

Using the XPath API in Flash

:: October 21, 2005

What is XPath?

XPath is a simple way by which you search through a XML document. It lets you query XML documents using names instead of the firstChild.childNodes... method.
If you are looking for a detailed explanation you can find one here : XML Path Language (XPath). This is what is mentioned in Macromedia LiveDocs about the use of XPath:

"The XPathAPI class allows you to do simple XPath searches within Macromedia Flash. This can be very useful for searching XML packets based on node names and attribute values. In other words, you can quickly find nodes and attributes in an XML document using the XpathAPI methods."

At this point I have to mention that Flash does not support all the functionalities of XPath API as defined by the XPath standard documents. Flash provides support to only a small subset of the XPath API.

What's the use of XPath?

XPath saves lot of time which you spend figuring out which node/s you want to target and retrieve value from. XPath existed from MX2004 days but wasn't documented, but in Flash 8 it is documented. Flash 8's in build help doesn't provide much of details on using XPath but there is a link to the LiveDocs which points to a PDF file which has all the public methods listed and examples for using them.

How to use XPath in Flash?

There are two things that you have to do to get XPath working. The first is to import the XPathAPI class like this:

import mx.xpath.XPathAPI;

and next to have a instance of DataBinding classes (Window > Common Libraries > Classes) in your document. You can drag a instance of the DataBinding class into your document.

Now you are ready to start using the XPath API.

The XPath API class contains the following public methods:

XPathAPI.getEvalString()
XPathAPI.selectNodeList()
XPathAPI.selectSingleNode()
XPathAPI.setNodeValue()

In this tutorial I am going to deal with two of these API's XPathAPI.selectNodeList() and XPathAPI.selectSingleNode()

XPathAPI.selectNodeList()

This method retrieves the nodes of a specified node path.

Syntax:

XPathAPI.selectNodeList(node, path)

Let’s start with an example XML of the site index of this site

Have a look at the actual XML here.

Now if I want to retrieve the value of all the title's, the path would be \rss\channel\item\title and the node would be this.firstChild.
So in this case I would use the selectNodeList as:

XPathAPI.selectNodeList(this.firstChild, "/rss/channel/item/title");

This statement would return me the array of all the titles.

Example:

import mx.xpath.XPathAPI;

var rss:XML = new XML();
rss.ignoreWhite = true;
rss.onLoad = function(success:Boolean) {
if (success) {
// Retrieve all titles in the path /rss/channel/item/title.
var titleArray:Array = XPathAPI.selectNodeList(this.firstChild, "/rss/channel/item/title");
for (var i:Number = 0; i < titleArray.length; i++) {
trace(titleArray[i].firstChild.nodeValue);
}
} else {
trace("XML loading failed !!!");
}
};
rss.load("http://www.lastashero.com/tutorials/index.xml");

This code will trace the following values in the output window :

Automating Meta Data insertion using JSAPI
Using SWF Metadata in Flash 8
Creating a File upload application using FileReference API
Using the onHTTPStatus handler
Flash 8 - Object Drawing Model

XPathAPI.selectSingleNode()

XPathAPI.selectSingleNode method is very similar to XPathAPI.selectNodeList, except for the fact that XPathAPI.selectSingleNode retreives the value of a single node instead of multiple nodes as in XPathAPI.selectNodeList.

Syntax:

XPathAPI.selectSingleNode(node, path)

Going by the old example, if you want to retrieve the value of the first title node the code would be :

import mx.xpath.XPathAPI;

var rss:XML = new XML();
rss.ignoreWhite = true;
rss.onLoad = function(success:Boolean) {
if (success) {
// Retrieve the title of the first node in the path /rss/channel/item/title.
var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/channel/item/title");
trace(titleNode.toString());
} else {
trace("XML loading failed !!!");
}
};
rss.load("http://www.lastashero.com/tutorials/index.xml");

This code will trace the following values in the output window :

<title>Automating Meta Data insertion using JSAPI</title>

The following path expressions can be used for the query:

Absolute path :

/item/title

Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/channel/item/title");

Relative path :

title (if the context node is )

Example: Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "title");

Wildcard (*) :

/*/title - retrieves all <title> elements,whatever the parent node is

Example : var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/*/title");

Predicate expressions using =, AND, or OR :

/item/title[@version='current']
or:
/item/title[@version='current' AND
@post='today']

Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/item/title[@version='current' AND @post='today']");

Documentation:

You can download the PDF from LiveDocs which contains all the methods and the usage from here.

If you have Flash 8 Pro / MX2004 Pro installed you can check out the actual class here :

C:\Documents and Settings\[User]\Local Settings\Application Data\Macromedia\Flash 8\[Language]\Configuration\Classes\mx\xpath\

Related readings:

XPath in Flash
Using XPath with Flash
XPath in Flash - there's always more than one way to go
Using XPath in Flash


Automating Meta Data insertion using JSAPI

:: October 18, 2005

As I mentioned in my previous post on Using Metadata in Flash 8, you can automate the process of inserting meta data into your Flash document by using JSAPI commands.

The code below creates a new FLA and addes the Title and Description to the newly created document.


// Create a new timeline-based FLA document

fl.createDocument();


// Retreive the document object (DOM) for the active FLA

doc = fl.getDocumentDOM();


// Intialize a variable with the current date

var today = new Date();


// Intialize a variable with the Title of the document

var docTitle = "Last ActionScript Hero : SWF Metadata Tutorial";

// Intialize a variable with the Description of the document

var docDesc = "This is a tutorial that teaches how to use SWF Metadata in Flash 8";

// Create a RDF XML in the specified syntax using current date, title and description

var rdfXML = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/1.1/" dc:title="'+ docTitle +'" dc:description="' + docDesc+'" /><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:CreateDate="'+ today +'" xmp:CreatorTool="Flash Authoring WIN 8,0,0,215" /></rdf:RDF>';

// Add the RDF XML to the current document (Sets the meta data)
doc.setMetadata(rdfXML);


Copy & Paste the above code in a new JSFL file and save it as CreateDoc.jsfl and move this file to the commands folder : C:\Documents and Settings\<user>\Local Settings\Application Data\Macromedia\Flash 8\<language>\Configuration\Commands\

Restart Flash and choose Commands > CreateDoc

This will create a new FLA document with the specified Title and Description.

Donwload : CreateDoc.zip

Using SWF Metadata in Flash 8

:: October 17, 2005

What is SWF Metadata?

Simply put SWF Metadata is something similar to HTML meta tags. SWF Metadata is a new feature in Flash 8 that helps search engines like Google index Flash contents. This was something which was not directly possible in Flash and people used to rely on workarounds to achieve this. SWF Metadata is specified in RDF (Resource Description Framework) which is stored in the SWF which search engines can use to find relevant keywords.

How to use SWF Metadata?

The metadata for a Flash document can be specified in the document properties (Modify > Document... [Ctrl+J]). You will find two text areas titled "Title" and "Description". These are the two values which are used as the SWF Metadata for the document.

After you have specified these two values and compile your movie, the metadata values are added to the header of the SWF file which the search engine can use to index your content.

Other ways of specifying SWF metadata

If you are webmaster and want to include a standard set of keywords/title/description for all your Flash content, the JSAPI DOM provides methods by which you can insert such title and description into your document. You can set metadata using the JSAPI function document.setMetadata(). The setMetadata function takes a XML as the parameter and sets the metadata of the document. The XML that is passed to the setMetadata function can be in three formats. The various formats are described here.

The simplest form of which is :

<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>
<rdf:Description rdf:about='' xmlns:dc='http://purl.org/dc/1.1/' dc:title='Last ActionScript Hero : SWF Metadata Tutorial' dc:description='This is a tutorial that teaches how to use SWF Metadata in Flash 8' />
<rdf:Description rdf:about='' xmlns:xmp='http://ns.adobe.com/xap/1.0/' xmp:CreateDate='2004-10-12T10:29-07:00' xmp:CreatorTool='Flash Authoring WIN 8,0,0,215' />
</rdf:RDF>

Is SWF Metadata used by all popular search engines to index contents?

The answer is NO. Not all popular search engines are build to index pages that have SWF metadata. Google for sure does this though. Do you really bother about others ;)

How do I make sure the metadata I specified for my document is embeded into the SWF?

Simple, if you look at the size report generated by Flash for your movie, you will see a row titled "Metadata" which will look like this :

meta.swf Movie Report
----------------------
Metadata
--------
Bytes Value
----- -----
227 <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/1.1/"><dc:title>Last ActionScript Hero : SWF Metadata Tutorial</dc:title><dc:description>This is a tutorial that teaches how to use SWF Metadata in Flash 8</dc:description></rdf:Description></rdf:RDF>

To generate size report for you movie goto File > Publish Settings... > Flash > Options and check the "Generate Size Report" checkbox.

How do I search Google for SWF's that has SWF metadata embeded in them?

You can do a search by filetype and keywords in Google. For example a search for filetype:swf +"tutorial" in Google would return those SWF's which are associated with the keyword tutorial in them.

If you are looking for a specific SWF in a specific site you can use the site: and filetype: keywords in Google to specify the exact filename you are looking for in a site.

Example :

filetype:swf site:lastashero.com

Creating a File upload application using FileReference API

:: October 08, 2005

Feature - FileReference API
Level - Intermediate
Audience - Developers

FileReference API provides methods using which one can download or upload files from/to a server. Each FileReference object maps to a single file which can be uploaded or downloaded from/to a server. You can get the following properties of a file using the FileReference API:

  • File Size
  • File Type
  • File Name
  • Creation Date
  • Modification Date
  • Creator type (Mac only)

Due to security reasons you CANNOT get the file path of the file which you are uploading to the server.

The following methods are available in the FileReference API:

and the events are:

onCancel = function(fileRef:FileReference) {}

Invoked when the user dismisses the file-browsing dialog box.

Ex: 

listener.onCancel = function(file:FileReference):Void {

    log.addItem(“File upload/download cancelled by user”);

}

onComplete = function(fileRef:FileReference) {}

Invoked when the upload or download operation has successfully completed.

Ex:

listener.onComplete = function(file:FileReference):Void {

    log.addItem(“File upload/download successful”);

    // Write code here to do manipulations or display the uploaded file

}

onHTTPError = function(fileRef:FileReference, httpError:Number) {}

Invoked when an upload fails because of an HTTP error.

Note: This event applies only to File Upload and not File Download. If a file download fails, an IO Error is reported instead of a HTTP Error.

Ex:

listener.onHTTPError = function(file:FileReference, httpError:Number):Void {

    log.addItem(“HTTP Error :” + httpError);

    // Write code here to do corrective actions

}

onIOError = function(fileRef:FileReference) {}
Invoked when an input/output error occurs.

onOpen = function(fileRef:FileReference) {}
Invoked when an upload or download operation starts.

onProgress = function(fileRef:FileReference, bytesLoaded:Number, bytesTotal:Number) {}Invoked periodically during the file upload or download operation.

Ex:

listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {

log.addItem("bytesLoaded: " + bytesLoaded + " bytesTotal: " + bytesTotal);

}

onSecurityError = function(fileRef:FileReference, errorString:String) {}
Invoked when an upload or download fails because of a security error.

Note: In most of the cases this error occurs due to the sandbox restriction. Check if the crossdomain.xml file is present and configured properly in the site to which you are uploading the file.

Ex:

listener.onSecurityError = function(file:FileReference, errorString:String):Void {

   log.addItem("Security Error: " + file.name + " errorString: " + errorString);

}

onSelect = function(fileRef:FileReference) {}
Invoked when the user selects a file to upload or download from the file-browsing dialog box.

Ok, enough of lecture. Let’s get into implementing a example using FileReference API which will be a application through which you can upload files into a web server.

So what do you need to implement this example?

  • The Flash application
  • A PHP/ASP/JSP page which will catch the file stream and create the file on the server
  • A folder on the Web server with write permission.

Flash application:

This file contains all the methods that are present in the FileReference and the usage example.

PHP code:

<?PHP
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['Filedata']['name']);

if(move_uploaded_file($_FILES['Filedata']['tmp_name'], $target_path))
{
     echo "The file ". basename( $_FILES['Filedata']['name']). " has been uploaded";
}
else
{
     echo "There was an error uploading the file, please try again!";
}
?>

For a detailed explanation of this code, see here.

Download the example files here.

Just unzip the archive into a folder and upload it to your web server and you are ready to upload files into the server.

Additional References :

Flash 8 File-Upload (RC-1)
Uploading files with Flash 8
Flash: Force Download… No more dirty tricks in Flash 8

Using the onHTTPStatus handler

:: October 02, 2005

Feature   -   httpStatus
Level       -   Intermediate
Audience -   Developers

What is HTTP status?

In general a HTTP status is received by the browser from the server when a URL is requested. In case of Flash, the Flash player recieves a HTTP status from the server when a call is made. HTTP status messages need not be always errors. W3C clasifies HTTP status into 5 different categories based on the types of status. You can find the different types of status here.

Use of HTTP status

There are many uses of HTTP status but the primary use is to debug the application. Based on the HTTP status that is received by your application you can write code to handle a case. This is particulary crusial when creating RIA's using Flash. For instance if you are writing a application which aggregates data from different RSS feeds and if some of the servers are down then your application may not work as intended and you would spend a lot of time debugging your application, whereas the actual problem is in the server side and not with your applications. In these kind of situations HTTP status methods comes handy and can save you a lot of development time.

Flash &HTTP status

httpStaus is a new method in Flash 8 which provides a way to get the HTTP status code when trying to load data into Flash. httpStatus can be used mainly with XML and LoadVars.

LoadVars.onHTTPStatus
XML.onHTTPStatus

In the past there was no method in Flash by which you can do this except for the Log class which is used with WebServices.

Usage:

The onHTTPStatus handler is called before the onData call. The onData handler will pass undefined to onLoad handler if the loading fails .

Example:

#include "httpCodes.as"

var myXml:XML = new XML();

myXml.onHTTPStatus = function(httpStatus:Number) {
for (var i=0; i<codeArray.length; i++)
{
var errString:String;
errString = httpStatus.toString();
if (codeArray[i].indexOf(errString)>-1)
{
trace(codeArray[i])
}
}
}

myXml.load("http://www.lastashero.com/blog/index.xml");



The file httpCodes.as contains the various HTTP status codes and a very brief status message. You can download the file httpCodes.as here.

Just copy and paste the above code in your main timeline and compile the movie. The output window will display the message "200 - OK", which implies that the request has succeeded.

Now for a negative case :

Copy & paste the same code above but modify the last line from : myXml.load("http://www.lastashero.com/blog/index.xml"); to myXml.load("http://www.lastashero.com/blog/index1.xml");
Now when you compile the movie, since index1.xml does not exists on the server your output window will display the message "404 - Not Found". Which is the famous Page Not Found error.

If you want to take decisions based on the type of HTTP status, you can use the code which comes with the examples in Flash 8. So if the status is Information or Success messages you can trivially ignore them and if they are error messages, you can take corrective measures based on the error code.

Additional Resources :

LoadVars.onHTTPStatus
XML.onHTTPStatus

Sample:

This SWF queries various feeds listed in MXNA and returns the status. This is a quick example which I constructed and the code is not optimized, once I come up with a proper example I will post the file here.

Flash 8 - Object Drawing Model

:: September 27, 2005

Feature   -   Object Drawing Model
Level       -   Beginner
Audience -   Designers

What is Object Drawing Model?

OBD is a new drawing model in Flash 8 which allows users to draw overlapping shapes which doesn't combine into a single object as it used to in previous versions.

How to enable this feature?

Select any of these tools :

  1. Line Tool
  2. Pen Tool
  3. Pencil Tool
  4. Brush Tool
  5. Polygon Tool
  6. Oval Tool or
  7. Rectangle Tool

Before you draw a shape select the Object Drawing mode in the Options section.

Now when you draw a shape the shape will be drawn using the Object Drawing Model.

How is OBD different from grouping?

In a outlook both OBD and grouping is looks alike; but there are a lot of operations which you can perform on a shape drawn using OBD, which you can't when the shape is grouped. Some of them are :

  1. You can change the fill and stroke color of a shape drawn using OBD but you can't do the with in a grouped shape.
  2. You can use Distort , Envelope and other transformations on a OBD shape which you can't with grouped shapes.

and a lot more like Combining Objects.

Additional operations using OBD

With two overlapping OBD shapes you can perform combine operations on them using Union, Intersect, Punch and Crop.

JS API Methods

  • document.deleteEnvelope()
  • document.intersect()
  • document.punch()
  • document.union()
  • shape.isDrawingObject
  • document.crop()

Detailed description of these methods can be found in the Flash 8 inbuild help system or Live Docs.

OBD in action

Click this image to download the demo of the feature.

Comments & Questions

Please drop in your comments / questions in the comments section.