What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Work with External Data in Flash

Creating Interaction with ActionScript

About events and interaction

Controlling SWF file playback

Jumping to a frame or scene

Playing and stopping movie clips

Jumping to a different URL

Creating a custom mouse pointer

Getting the pointer position

Capturing keypresses

Setting color values

Creating sound controls

Detecting collisions

Creating a simple line drawing tool

Creating runtime data bindings using ActionScript

Creating bindings between UI components using ActionScript

Using components, bindings, and custom formatters

Adding and binding components on the Stage

Deconstructing a sample script

Working with External Data

TOP

In Macromedia Flash Basic 8 and Macromedia Flash Professional 8, you can use ActionScript to load data from external sources to a SWF file.You can also send data, which could be provided by the user or the server, from a SWF file to an application server (such as Macromedia ColdFusion or Macromedia JRun) or another type of server-side script, such as PHP or Perl.

Macromedia Flash Player can send and load data over HTTP or HTTPS or load from a local text file. You can also create persistent TCP/IP socket connections for applications that require low latency--for example, chat applications or stock quote services. New in Flash Player 8 is the ability to upload files from the user's computer to a server and download files from a server to the user's computer.

Data that you load into or send from a SWF file can be formatted as XML (Extensible Markup Language) or as name-value pairs.

Flash Player can also send data to and receive data from its host environment--a web browser, for example--or another instance of Flash Player on the same computer or web page.

By default, a SWF file can access only data that resides in exactly the same domain (for example, www.macromedia.com). (For more information, see About domains, cross-domain security, and SWF files.)
 

Sending and loading variables

TOP

A SWF file is a window for capturing and displaying information, much like an HTML page. However, SWF files can stay loaded in the browser and continuously update with new information without having to reload the entire page. Using ActionScript functions and methods, you can send information to and receive information from server-side scripts and receive information from text files and XML files.

In addition, server-side scripts can request specific information from a database and relay it to a SWF file. Server-side scripts can be written in different languages: some of the most common are CFML, Perl, ASP (Microsoft Active Server Pages), and PHP. By storing information in a database and retrieving it, you can create dynamic and personalized content for your SWF file. For example, you could create a message board, personal profiles for users, or a shopping cart that keeps track of a user's purchases.

Several ActionScript functions and methods let you pass information into and out of a SWF file. Each function or method uses a protocol to transfer information and requires information to be formatted in a certain way.

The functions and MovieClip methods that use the HTTP or HTTPS protocol to send information in URL-encoded format are getURL(), loadVariables(), loadVariablesNum(), loadMovie(), and loadMovieNum().

The LoadVars methods that use the HTTP or HTTPS protocol to send and load information in URL-encoded format are load(), send(), and sendAndLoad().

The methods that use HTTP or HTTPS protocol to send and load information as XML are XML.send(), XML.load(), and XML.sendAndLoad().

The methods that create and use a TCP/IP socket connection to send and load information as XML are XMLSocket.connect() and XMLSocket.send().
 

Checking for loaded data

TOP

Each function or method that loads data into a SWF file (except XMLSocket.send()) is asynchronous: the results of the action are returned at an indeterminate time.

Before you can use loaded data in a SWF file, you must check to see whether it has been loaded. For example, you can't load variables and manipulate their values in the same script because the data to manipulate doesn't exist in the file until it is loaded. In the following script, you cannot use the variable lastSiteVisited until you're sure that the variable has loaded from the file myData.txt. In the file myData.txt, you would have text similar to the following example:

lastSiteVisited=www.macromedia.com

If you used the following code, you could not trace the data that is loading:

loadVariables("myData.txt", 0);

trace(lastSiteVisited); // undefined

Each function or method has a specific technique you can use to check data it has loaded. If you use loadVariables function or loadMovie function, you can load information into a movie clip target and use the onData handler to execute a script. If you use loadVariables function to load the data, the onData handler executes when the last variable is loaded. If you use loadMovie function to load the data, the onData handler executes each time a fragment of the SWF file is streamed into Flash Player.

For example, the following ActionScript loads the variables from the file myData.txt into the movie clip loadTarget_mc. An onData() handler assigned to the loadTarget_mc instance uses the variable lastSiteVisited, which is loaded from the file myData.txt. The following trace actions appear only after all the variables, including lastSiteVisited, are loaded:

this.createEmptyMovieClip("loadTarget_mc", this.getNextHighestDepth());

this.loadTarget_mc.onData = function() {

trace("Data Loaded");

trace(this.lastSiteVisited);

};

loadVariables("myData.txt", this.loadTarget_mc);

If you use the XML.load(), XML.sendAndLoad(), and XMLSocket.connect() methods, you should define a handler that processes the data when it arrives. This handler is a property of an XML or XMLSocket object to which you assign a function you defined. The handlers are called automatically when the information is received. For the XML object, use XML.onLoad() or XML.onData(). For the XMLSocket object, use XMLSocket.onConnect().

 

Creating a progress bar to display data loading progress

TOP

The following exercise dynamically creates a simple preloader using the Drawing application programming interface (API) and displays the loading progress for an XML document.

TIP : If the remote XML file loads too quickly to see the preloading effect, try uploading a larger XML file to the internet and loading that file.

Creating a progress bar using the Drawing API:

  1. Create a new Flash document and save it as drawapi.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var barWidth:Number = 200;

    var barHeight:Number = 6;

    this.createEmptyMovieClip("pBar_mc", 9999);

    var bar:MovieClip = pBar_mc.createEmptyMovieClip("bar_mc", 10);

    bar.beginFill(0xFF0000, 100);

    bar.moveTo(0, 0);

    bar.lineTo(barWidth, 0);

    bar.lineTo(barWidth, barHeight);

    bar.lineTo(0, barHeight);

    bar.lineTo(0, 0);

    bar.endFill();

    bar._xscale = 0;

    var stroke:MovieClip = pBar_mc.createEmptyMovieClip("stroke_mc", 20);

    stroke.lineStyle(0, 0x000000);

    stroke.moveTo(0, 0);

    stroke.lineTo(barWidth, 0);

    stroke.lineTo(barWidth, barHeight);

    stroke.lineTo(0, barHeight);

    stroke.lineTo(0, 0);

    pBar_mc.createTextField("label_txt", 30, 0, barHeight, 100, 21);\

    pBar_mc.label_txt.autoSize = "left";

    pBar_mc.label_txt.selectable = false;

    pBar_mc._x = (Stage.width - pBar_mc._width) / 2;

    pBar_mc._y = (Stage.height - pBar_mc._height) / 2;

    var my_xml:XML = new XML();

    my_xml.ignoreWhite = true;

    my_xml.onLoad = function(success:Boolean) {

    pBar_mc.onEnterFrame = undefined;

    if (success) {

    trace("XML loaded successfully");

    } else {

    trace("Unable to load XML");

    }

    };

    my_xml.load("http://www.helpexamples.com/flash/xml/ds.xml");

    pBar_mc.onEnterFrame = function() {

    var pctLoaded:Number = Math.floor(my_xml.getBytesLoaded() / my_xml.getBytesTotal() * 100);

    if (!isNaN(pctLoaded)) {

    pBar_mc.bar_mc._xscale = pctLoaded;

    pBar_mc.label_txt.text = pctLoaded + "% loaded";

    if (pctLoaded >= 100) {

    pBar_mc.onEnterFrame = undefined;

    }

    }

    };

    The previous code is broken down into seven sections. The first section defines the width and height of the progress bar when it is drawn on the Stage. The progress bar will be centered on the Stage in an upcoming section. The next section of code creates two movie clips, pBar_mc and bar_mc. The bar_mc movie clip is nested inside pBar_mc, and draws a red rectangle on the Stage. The bar_mc instance modifies its _xscale property as the external XML file loads from the remote website.

    Next, a second movie clip is nested inside of the pBar_mc movie clip, stroke_mc. The stroke_mc movie clip draws an outline on the Stage that matches the dimensions specified by the barHeight and barWidth variables defined in the first section. The fourth section of code creates within the pBar_mc movie clip a text field that is used to display what percentage of the XML file has already loaded, similar to the label on the ProgressBar component. Next, the pBar_mc movie clip (which includes the nested bar_mc, stroke_mc, and label_txt instances) is centered on the Stage.

    The sixth section of code defines a new XML object instance, which is used to load an external XML file. An onLoad event handler is defined and traces a message to the Output panel. The onLoad event handler also deletes the onEnterFrame event handler (which is defined in the next section) for the pBar_mc movie clip. The final section of code defines an onEnterFrame event handler for the pBar_mc movie clip. This event handler monitors how much of the external XML file has loaded and modifies the _xscale property for the bar_mc movie clip. First the onEnterFrame event handler calculates what percentage of the file has finished downloading. As long as the percentage of the file loaded is a valid number, the _xscale property for bar_mc is set, and the text field within pBar_mc displays what percentage of the file has loaded. If the file has completed loading (percent loaded reaches 100%) the onEnterFrame event handler is deleted so download progress is no longer monitored.

  3. Select Control > Test Movie to test the Flash document.

As the external XML file loads, the nested bar_mc movie clip resizes to display the download progress of the XML. Once the XML file has completely loaded, the onEnterFrame event handler gets deleted so it doesn't continue to calculate the download progress. Depending on how fast the download completes, you should be able to see the bar slowly grow until the bar_mc is the same width as the stroke_mc movie clip. If the download occurs too fast, the progress bar may go from 0% to 100% too quickly, making the effect harder to see; in this case it may be necessary to try downloading a larger XML file.
 

Using HTTP to connect to server-side scripts

TOP

The loadVariables function, loadVariablesNum function, getURL function, loadMovie function, loadMovieNum function functions and the loadVariables (MovieClip.loadVariables method), loadMovie (MovieClip.loadMovie method), and getURL (MovieClip.getURL method) methods can communicate with server-side scripts using HTTP or HTTPS protocols.These functions and methods send all the variables from the timeline to which the function is attached. When used as methods of the MovieClip object, loadVariables(), getURL(), and loadMovie() send all the variables of the specified movie clip; each function (or method) handles its response as follows:

  • The getURL() function returns any information to a browser window, not to Flash Player.

  • The loadVariables() method loads variables into a specified timeline or level in Flash Player.

  • The loadMovie() method loads a SWF file into a specified level or movie clip in Flash Player.

When you use loadVariables(), getURL(), or loadMovie(), you can specify several parameters:

  • URL is the file in which the remote variables reside.

  • Location is the level or target in the SWF file that receives the variables. (The getURL() function does not take this parameter.)

  • Variables sets the HTTP method, either GET (appends the variables to the end of the URL) or POST (sends the variables in a separate HTTP header), by which the variables are sent. When this parameter is omitted, Flash Player defaults to GET, but no variables are sent.

For example, if you want to track the high scores for a game, you could store the scores on a server and use loadVariables() to load them into the SWF file each time someone played the game. The function call might look like the following example:

this.createEmptyMovieClip("highscore_mc", 10);

loadVariables("http://www.helpexamples.com/flash/highscore.php", highscore_mc, "GET");

This example loads variables from the ColdFusion script called high_score.cfm into the movie clip instance scoreClip using the GET HTTP method.

Any variables loaded with the loadVariables() function must be in the standard MIME format application/x-www-form-urlencoded (a standard format used by CFM and CGI scripts). The file you specify in the URL parameter of loadVariables() must write out the variable and value pairs in this format so that Flash can read them. This file can specify any number of variables; variable and value pairs must be separated with an ampersand (&), and words within a value must be separated with a plus (+) sign. For example, the following phrase defines several variables:

highScore1=54000&playerName1=RGoulet&highScore2=53455&playerName2=

WNewton&highScore3=42885&playerName3=TJones

NOTE : You might need to URL-encode certain characters, such as the plus (+) sign or ampersand (&) characters. For more information, see www.macromedia.com/go/tn_14143.
 

Using the LoadVars class

TOP

If you are publishing to Flash Player 6 or later and want more flexibility than loadVariables() offers, you can use the LoadVars class instead to transfer variables between a SWF file and a server.

The LoadVars class was introduced in Flash Player 6 to provide a cleaner, more object-oriented interface for the common task of exchanging CGI data with a web server. Advantages of the LoadVars class include the following:

  • You don't need to create container movie clips for holding data or clutter existing movie clips with variables specific to client/server communication.

  • The class interface is similar to that of the XML object, which provides some consistency in ActionScript. It uses the methods load(), send(), and sendAndLoad() to initiate communication with a server. The main difference between the LoadVars and XML classes is that the LoadVars data is a property of the LoadVars object rather than of an XML Document Object Model (DOM) tree stored in the XML object.

  • The class interface is more straightforward--with methods named load, send, sendAndLoad--than the older loadVariables interface.

  • You can get additional information about the communication, using the getBytesLoaded and getBytesTotal methods.

  • You can get progress information about the download of your data (although you can't access the data until it is fully downloaded).

  • The callback interface is through ActionScript methods (onLoad) instead of the obsolete, deprecated onClipEvent (data) approach required for loadVariables.

  • There are error notifications.

  • You can add custom HTTP request headers.

You must create a LoadVars object to call its methods. This object is a container to hold the loaded data.

The following procedure shows how to use ColdFusion and the LoadVars class to send an e-mail from a SWF file.

NOTE : You must have ColdFusion installed on your web server for this example.

To load data with the LoadVars object:

  1. Create a CFM file in Macromedia Dreamweaver or in your favorite text editor. Add the following text to the file:

    <cfif StructKeyExists(Form, "emailTo")>

    <cfmail to="#Form.emailTo#" from="#Form.emailFrom#" subject="#Form.emailSubject#">#Form.emailBody#</cfmail>

    &result=true

    <cfelse>

    &result=false

    </cfif>

  2. Save the file as email.cfm, and upload it to your website.

  3. In Flash, create a new document.

  4. Create four input text fields on the Stage, and give them the following instance names: emailFrom_txt, emailTo_txt, emailSubject_txt, and emailBody_txt.

  5. Create a dynamic text field on the Stage with the instance name debug_txt.

  6. Create a button symbol, drag an instance on to the Stage, and give it an instance name of submit_btn.

  7. Select Frame 1 in the Timeline, and open the Actions panel (Window > Actions) if it isn't already open.

  8. Enter the following code in the Actions panel:

    this.submit_btn.onRelease = function() {

    var emailResponse:LoadVars = new LoadVars();

    emailResponse.onLoad = function(success:Boolean) {

    if (success) {

    debug_txt.text = this.result;

    } else {

    debug_txt.text = "error downloading content";

    }

    };

    var email:LoadVars = new LoadVars();

    email.emailFrom = emailFrom_txt.text;

    email.emailTo = emailTo_txt.text;

    email.emailSubject = emailSubject_txt.text;

    email.emailBody = emailBody_txt.text;

    email.sendAndLoad("http://www.yoursite.com/email.cfm", emailResponse, "POST");

    };

    This ActionScript creates a new LoadVars object instance, copies the values from the text fields into the instance, and then sends the data to the server. The CFM file sends the e-mail and returns a variable (true or false) to the SWF file called result, which appears in the debug_txt text field.

    NOTE : Remember to change the URL www.yoursite.com to your own domain.

  9. Save the document as sendEmail.fla, and then publish it by selecting File > Publish.

  10. Upload sendEmail.swf to the same directory that contains email.cfm (the ColdFusion file you saved and uploaded in step 2).

  11. View and test the SWF file in a browser.

Flash Player 8 introduced the onHTTPStatus event handler for the LoadVars class, XML class, and MovieClipLoader class to allow users to access the status code from an HTTP request. This allows developers to determine why a particular load operation may have failed instead of only being able to determine that a load operation already has failed.

The following example shows how you can use the LoadVars class's onHTTPStatus event handler to check whether a text file successfully downloaded from the server and what the status code returned from the HTTP request was.

To check HTTP status with the LoadVars object:

  1. Create a new Flash document and save it as loadvars.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    this.createTextField("params_txt", 10, 10, 10, 100, 21);

    params_txt.autoSize = "left";

    var my_lv:LoadVars = new LoadVars();

    my_lv.onHTTPStatus = function(httpStatus:Number) {

    trace("HTTP status is: " + httpStatus);

    };

    my_lv.onLoad = function(success:Boolean) {

    if (success) {

    trace("text file successfully loaded");

    params_txt.text = my_lv.dayNames;

    } else {

    params_txt.text = "unable to load text file";

    }

    };

    my_lv.load("http://www.helpexamples.com/flash/404.txt");

    /* output:

    Error opening URL "http://www.helpexamples.com/flash/404.txt"

    HTTP status is: 404

    */

    The previous code creates a new text field on the Stage and enables text field autosizing. Next, a LoadVars object is created and two event handlers: onHTTPStatus and onLoad. The onHTTPStatus event handler is new to Flash Player 8 and is invoked when a LoadVars.load() or LoadVars.sendAndLoad() operation has completed. The value passed to the onHTTPStatus event handler function (httpStatus in the previous code) contains the HTTP status code definition for the current load operation. If the SWF file was able to successfully load the text file, the value of httpStatus is set to 200 (HTTP status code for "OK"). If the file didn't exist on the server, the value of httpStatus is set to 404 (HTTP status code for "Not Found"). The second event handler, LoadVars.onLoad(), gets called after the file has finished loading. If the file successfully loaded, the value of the success parameter is set to true, otherwise the success parameter is set to false. Finally, the external file is loaded using the LoadVars.load() method.

  3. Select Control > Test Movie to test the Flash document.

Flash displays an error message to the Output panel stating that it was unable to load the image because it doesn't exist on the server. The onHTTPStatus event handler traces the status code of 404 since the file could not be found on the server, and the onLoad event handler sets the params_txt text field's text property to "unable to load text file."

CAUTION : If a web server does not return a status code to the Flash Player, the number 0 is returned to the onHTTPStatus event handler.

 

About file uploading and downloading

TOP

The FileReference class lets you add the ability to upload and download files between a client and server. Your users can upload or download files between their computer and a server. Users are prompted to select a file to upload or a location for download in a dialog box (such as the Open dialog box on the Windows operating system).

Each FileReference object that you create with ActionScript refers to a single file on the user's hard disk. The object has properties that contain information about the file's size, type, name, creation date, and modification date. On the Macintosh, there is also a property for the file's creator type.

You can create an instance of the FileReference class in two ways. You can use the following new operator:

import flash.net.FileReference;

var myFileReference:FileReference = new FileReference();

Or, you can call the FileReferenceList.browse() method, which opens a dialog box on the user's system to prompt the user to select a file to upload and then creates an array of FileReference objects if the user selects one or more files successfully. Each FileReference object represents a file selected by the user from the dialog box. A FileReference object does not contain any data in the FileReference properties (such as name, size, or modificationDate) until the FileReference.browse() method or FileReferenceList.browse() method has been called and the user has selected a file from the file picker or until the FileReference.download() method has been used to select a file from the file picker.

NOTE : FileReference.browse() lets the user select a single file. FileReferenceList.browse() lets the user select multiple files.

After a successful call to the browse() method, you call FileReference.upload() to upload one file at a time.

You can also add download functionality to your Flash application. The FileReference.download() method prompts end users for a location on their hard disks to save a file from a server. This method also initiates downloading from a remote URL. When using the download() method, only the FileReference.name property is accessible when the onSelect event is dispatched. The rest of the properties are not accessible until the onComplete event is dispatched.

NOTE : When a dialog box appears on the end-user's computer, the default location that appears in the dialog box is the most recently browsed folder (if that location can be determined) or the desktop (if the recent folder cannot be determined). The FileReference and FileReferenceList APIs do not let you set the default file location
 

About FileReference API functionality and security

TOP

Flash Player and the FileReference API (see About file uploading and downloading) support file uploading and downloading up to 100 MB. The FileReference API does not let the Flash application that initiates the file transfer do the following:

  • Access the uploaded or downloaded file

  • Access the path of the file on the user's computer

When a server requires authentication, the only potentially successful operation is to perform file downloading using the Flash Player browser plug-in. Uploading on all Flash players, or downloading through the stand-alone or external Flash Player, fails on a server that requires authentication. Use FileReference event listeners to determine whether operations completed successfully or to handle errors.

Both file uploading and downloading are restricted to the SWF file's domain, including any domains that you specify using a cross-domain policy file. You need to put a policy file on the server if the SWF file that initiates the uploading or downloading doesn't come from the same domain as the server. For more information on cross-domain policy files and security, see About domains, cross-domain security, and SWF files.

When calls to FileReference.browse(), FileReferenceList.browse(), or FileReference.download() are executing, playback of the SWF file pauses on the following platforms: Mac OS X Flash Player browser plug-ins, the Macintosh external Flash Player, and the Macintosh stand-alone player on Mac OS X 10.1 and earlier. The SWF file continues to run on all Windows players and in the Macintosh stand-alone Flash Player on Mac OS X 10.2 and later.

WARNING : When allowing users to upload files to a server, you should always be careful to check the file type before saving the file to the hard disk. For example, you wouldn't want to allow a user to upload a server-side script that could be used to delete folders or files on the server. If you only want to allow users to upload an image file, make sure the server-side script that uploads the files checks that the file being uploaded is a valid image.
 

Adding file upload functionality to an application

TOP


The following procedure shows you how to build an application that lets you upload image files to a server. The application lets users select an image on their hard disks to upload and then send it to a server. The image that they upload then appears in the SWF file that they used to upload the image.

Following the example that builds the Flash application is an example that details the server-side code. Remember that image files are restricted in size: you can only upload images that are 200K or smaller.

To build a FLA application using the FileReference API:

  1. Create a new Flash document and save it as fileref.fla.
  2. Open the Components panel, and then drag a ScrollPane component onto the Stage and give it an instance name of imagePane. (The ScrollPane instance is sized and repositioned using ActionScript in a later step.)
  3. Drag a Button component onto the Stage and give it an instance name of uploadBtn.
  4. Drag two Label components onto the Stage and give them instance names of imageLbl and statusLbl.
  5. Drag a ComboBox component onto the Stage and give it an instance name of imagesCb.
  6. Drag a TextArea component onto the Stage and give it an instance name of statusArea.
  7. Create a new movie clip symbol on the Stage, and open the symbol for editing (double-click the instance to open it in symbol-editing mode).
  8. Create a new static text field inside the movie clip, and then add the following text:

    The file that you have tried to download is not on the server.

    In the final application, this warning might appear for one of the following reasons, among others:

    • The image was deleted from the queue on the server as other images were uploaded.
    • The server did not copy the image because the file size exceeded 200K.
    • The type of file was not a valid JPEG, GIF, or PNG file.

    NOTE : The width of the text field should be less than the width of the ScrollPane instance (400 pixels); otherwise users have to scroll horizontally to view the error message
    Right-click the symbol in the Library and select Linkage from the context menu.

  9. Select the Export for ActionScript and Export in First Frame check boxes, and type Message into the Identifier text box. Click OK.
  10. Add the following ActionScript to Frame 1 of the Timeline:
  11. NOTE : The code comments include details about the functionality. A code overview follows this example.

    import flash.net.FileReference;

    imagePane.setSize(400, 350);

    imagePane.move(75, 25);

    uploadBtn.move(75, 390);

    uploadBtn.label = "Upload Image";

    imageLbl.move(75, 430);

    imageLbl.text = "Select Image";

    statusLbl.move(210, 390);

    statusLbl.text = "Status";

    imagesCb.move(75, 450);

    statusArea.setSize(250, 100);

    statusArea.move(210, 410);]

    /* The listener object listens for FileReference events. */

    var listener:Object = new Object();

    /* When the user selects a file, the onSelect() method is called, and passed a reference to the FileReference object. */

    listener.onSelect = function(selectedFile:FileReference):Void {

    /* Update the TextArea to notify the user that Flash is attempting to upload the image. */

    statusArea.text += "Attempting to upload " + selectedFile.name + "\n";

    /* Upload the file to the PHP script on the server. */]

    selectedFile.upload("http://www.helpexamples.com/flash/file_io/uploadFile.php");

    };

    /* When the file begins to upload, the onOpen() method is called, so notify the user that the file is starting to upload. */

    listener.onOpen = function(selectedFile:FileReference):Void {

    statusArea.text += "Opening " + selectedFile.name + "\n";

    };

    /* When the file has uploaded, the onComplete() method is called. */

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

    /* Notify the user that Flash is starting to download the image. */

    statusArea.text += "Downloading " + selectedFile.name + " to player\n";

    /* Add the image to the ComboBox component. */

    imagesCb.addItem(selectedFile.name);

    /* Set the selected index of the ComboBox to that of the most recently added image. */

    imagesCb.selectedIndex = imagesCb.length - 1;

    /* Call the custom downloadImage() function. */

    downloadImage();

    };

    var imageFile:FileReference = new FileReference();

    imageFile.addListener(listener);

    imagePane.addEventListener("complete", imageDownloaded);

    imagesCb.addEventListener("change", downloadImage);

    uploadBtn.addEventListener("click", uploadImage);

    /* If the image does not download, the event object's total property will equal -1. In that case, display a message to the user. */

    function imageDownloaded(event:Object):Void {

    if (event.total == -1) {

    imagePane.contentPath = "Message";

    }

    }

    /* When the user selects an image from the ComboBox, or when the downloadImage() function is called directly from the listener.onComplete() method, the downloadImage() function sets the contentPath of the ScrollPane in order to start downloading the image to the player. */

    function downloadImage(event:Object):Void {

    imagePane.contentPath = "http://www.helpexamples.com/flash/file_io/images/" + imagesCb.value;

    }

    /* When the user clicks the button, Flash calls the uploadImage() function, and it opens a file browser dialog box. */

    function uploadImage(event:Object):Void {

    imageFile.browse([{description: "Image Files", extension: "*.jpg;*.gif;*.png"}]);

    }

    This ActionScript code first imports the FileReference class and initializes, positions, and resizes each of the components on the Stage. Next, a listener object is defined, and three event handlers are defined: onSelect, onOpen, and onComplete. The listener object is then added to a new FileReference object named imageFile. Next, event listeners are added to the imagePane ScrollPane instance, imagesCb ComboBox instance, and uploadBtn Button instance. Each of the event listener functions is defined in the code that follows this section of code.

    The first function, imageDownloaded(), checks to see if the amount of total bytes for the downloaded images is -1, and if so, it sets the contentPath for the ScrollPane instance to the movie clip with the linkage identifier of Message, which you created in a previous step. The second function, downloadImage(), attempts to download the recently uploaded image into the ScrollPane instance. When the image has downloaded, the imageDownloaded() function defined earlier is triggered and checks to see whether the image successfully downloaded. The final function, uploadImage(), opens a file browser dialog box, which filters all JPEG, GIF, and PNG images.

  12. Save your changes to the document.
  13. Select File > Publish settings and then select the Formats tab, and make sure that Flash and HTML are both selected.
  14. (Optional) In the Publish Settings dialog box, select the Flash tab, and then select Access Network Only from the Local Playback Security pop-up menu.

    If you complete this step, you won't run into security restrictions if you test your document in a local browser.

  15. In the Publish Settings dialog box, click Publish to create the HTML and SWF files.

When you're finished, go on to the next procedure, in which you create the container for the SWF file.

The following procedure requires that PHP is installed on your web server and that you have write permissions to subfolders named images and temporary. You need to first complete the

previous procedure, or use the finished SWF file available in the previously noted folders.\

To create a server-side script for the image upload application:

  1. Create a new PHP document using a text editor such as Dreamweaver or Notepad.
  2. Add the following PHP code to the document. (A code overview follows this script.)

    <?php

    $MAXIMUM_FILESIZE = 1024 * 200; // 200KB

    $MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server

    echo exif_imagetype($_FILES['Filedata']);

    if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE) {

    move_uploaded_file($_FILES['Filedata']['tmp_name'], "./temporary/".$_FILES['Filedata']['name']);

    $type = exif_imagetype("./temporary/".$_FILES['Filedata']['name']);

    if ($type == 1 || $type == 2 || $type == 3) {

    rename("./temporary/".$_FILES['Filedata']['name'], "./images/".$_FILES['Filedata']['name']);

    } else {

    unlink("./temporary/".$_FILES['Filedata']['name']);

    }

    }

    $directory = opendir('./images/');

    $files = array();

    while ($file = readdir($directory)) {

    array_push($files, array('./images/'.$file, filectime('./images/'.$file)));

    }

    usort($files, sorter);

    if (count($files) > $MAXIMUM_FILE_COUNT) {

    $files_to_delete = array_splice($files, 0, count($files) - $MAXIMUM_FILE_COUNT);

    for ($i = 0; $i < count($files_to_delete); $i++) {

    unlink($files_to_delete[$i][0]);

    }

    }

    print_r($files);

    closedir($directory);]

    function sorter($a, $b) {

    if ($a[1] == $b[1]) {

    return 0;

    } else {

    return ($a[1] < $b[1]) ? -1 : 1;

    }

    }

    ?>

    This PHP code first defines two constant variables: $MAXIMUM_FILESIZE and $MAXIMUM_FILE_COUNT. These variables dictate the maximum size (in kilobytes) of an image being uploaded to the server (200KB), as well as how many recently uploaded files can be kept in the images folder (10). If the file size of the image currently being uploaded is less than or equal to the value of $MAXIMUM_FILESIZE, the image is moved to the temporary folder.

    Next, the file type of the uploaded file is checked to ensure that the image is a JPEG, GIF, or PNG. If the image is a compatible image type, the image is copied from the temporary folder to the images folder. If the uploaded file wasn't one of the allowed image types, it is deleted from the file system.

    Next, a directory listing of the image folder is created and looped over using a while loop. Each file in the images folder is added to an array and then sorted. If the current number of files in the images folder is greater than the value of $MAXIMUM_FILE_COUNT, files are deleted until there are only $MAXIMUM_FILE_COUNT images remaining. This prevents the images folder from growing to an unmanageable size, as there can be only 10 images in the folder at one time, and each image can only be 200KB or smaller (or roughly 2 MB of images at any time).

  3. Save your changes to the PHP document.
  4. Upload the SWF, HTML, and PHP files to your web server.
  5. View the remote HTML document in a web browser, and click the Upload Image button in the SWF file.
  6. Locate an image file on your hard disk and select Open from the dialog box.

The SWF file uploads the image file to the remote PHP document, and displays it in the ScrollPane (which adds scroll bars if necessary). If you want to view a previously uploaded image, you can select the filename from the ComboBox instance on the Stage. If the user tries to upload an image that isn't an allowed image type (only a JPEG, GIF, or PNG image is allowed) or the file size is too big (over 200 KB), Flash displays the error message from the Message movie clip in the Library.

 

About XML

TOP

Extensible Markup Language (XML) is becoming the standard for exchanging structured data in Internet applications. You can integrate data in Flash with servers that use XML technology to build sophisticated applications, such as chat or brokerage systems.

In XML, as with HTML, you use tags to specify, or mark up, a body of text. In HTML, you use predefined tags to indicate how text should appear in a web browser (for example, the <b> tag indicates that text should be bold). In XML, you define tags that identify the type of a piece of data (for example, <password>VerySecret</password>). XML separates the structure of the information from the way it appears, so the same XML document can be used and reused in different environments.

Every XML tag is called a node, or an element. Each node has a type (1, which indicates an XML element, or 3, which indicates a text node), and elements might also have attributes. A node nested in a node is called a child node. This hierarchical tree structure of nodes is called the XML DOM--much like the JavaScript DOM, which is the structure of elements in a web browser.

In the following example, <portfolio> is the parent node; it has no attributes and contains the child node <holding>, which has the attributes symbol, qty, price, and value:

<portfolio>

<holding symbol="rich"

qty="75"

price="245.50"

value="18412.50" />

</portfolio>

 

Using the XML class

TOP

The methods of the ActionScript XML class (for example, appendChild(), removeNode(), and insertBefore()) let you structure XML data in Flash to send to a server and manipulate and interpret downloaded XML data.

The following XML class methods send and load XML data to a server by using the HTTP POST method:

  • The load() method downloads XML from a URL and places it in an ActionScript XML object.

  • The send()method encodes the XML object into an XML document and sends it to a specified URL using the POST method. If specified, a browser window displays returned data.

  • The sendAndLoad() method sends an XML object to a URL. Any returned information is placed in an ActionScript XML object.

For example, you could create a brokerage system that stores all its information (user names, passwords, session IDs, portfolio holdings, and transaction information) in a database.

The server-side script that passes information between Flash and the database reads and writes the data in XML format. You can use ActionScript to convert information collected in the SWF file (for example, a user name and password) to an XML object and then send the data to the server-side script as an XML document. You can also use ActionScript to load the XML document that the server returns into an XML object to be used in the SWF file.

The flow and conversion of data between a SWF file, a server-side script, and a database

The password validation for the brokerage system requires two scripts: a function defined on Frame 1, and a script that creates and then sends the XML objects created in the document.
When a user enters information into text fields in the SWF file with the variables username and password, the variables must be converted to XML before being passed to the server. The first section of the script loads the variables into a newly created XML object called loginXML. When a user clicks a button to log in, the loginXML object is converted to a string of XML and sent to the server.

The following ActionScript is placed on the timeline and is used to send XML-formatted data to the server. To understand this script, read the commented lines (indicated by the characters //):

// ignore XML white space

XML.prototype.ignoreWhite = true;

// Construct an XML object to hold the server's reply

var loginReplyXML:XML = new XML();

// this function triggers when an XML packet is received from the server.

loginReplyXML.onLoad = function(success:Boolean) {

if (success) {

// (optional) Create two text fields for status/debugging

// status_txt.text = this.firstChild.attributes.status;

// debug_txt.text = this.firstChild;

switch (this.firstChild.attributes.STATUS) {

case 'OK' :

_global.session = this.firstChild.attributes.SESSION;

trace(_global.session);

gotoAndStop("welcome");

break;

case 'FAILURE' :

gotoAndStop("loginfailure");

break;

default :

// this should never happen

trace("Unexpected value received for STATUS.");

}

} else {

trace("an error occurred.");

}

};

// this function triggers when the login_btn is clicked

login_btn.onRelease = function() {

var loginXML:XML = new XML();

// create XML formatted data to send to the server

var loginElement:XMLNode = loginXML.createElement("login");

loginElement.attributes.username = username_txt.text;

loginElement.attributes.password = password_txt.text;

loginXML.appendChild(loginElement);

// send the XML formatted data to the server

loginXML.sendAndLoad("http://www.flash-mx.com/mm/main.cfm", loginReplyXML);

};

You can test this code by using a user name of JeanSmith and the password VerySecret. The first section of the script generates the following XML when the user clicks the login button:

<login username="JeanSmith" password="VerySecret" />

The server receives the XML, generates an XML response, and sends it back to the SWF file. If the password is accepted, the server responds with the following:

<LOGINREPLY STATUS="OK" SESSION="4D968511" />

This XML includes a session attribute that contains a unique, randomly generated session ID, which is used in all communications between the client and server for the rest of the session. If the password is rejected, the server responds with the following message:

<LOGINREPLY STATUS="FAILURE" />

The loginreply XML node must load into a blank XML object in the SWF file. The following statement creates the XML object loginreplyXML to receive the XML node:

// Construct an XML object to hold the server's reply

var loginReplyXML:XML = new XML();

loginReplyXML.onLoad = function(success:Boolean) {

The second statement in this ActionScript defines an anonymous (inline) function, which is called when the onLoad event triggers.

The login button (login_btn instance) is used to send the user name and password as XML to the server and to load an XML response back into the SWF file. You can use the sendAndLoad() method to do this, as shown in the following example:

loginXML.sendAndLoad("http://www.flash-mx.com.com/mm/main.cfm", loginReplyXML);

First, the XML-formatted data is created, using the values that the user inputs in the SWF file, and that XML object is sent using the sendAndLoad method. Similar to data from a loadVariables() function, the loginreply XML element arrives asynchronously (that is, it doesn't wait for results before being returned) and loads into the loginReplyXML object. When the data arrives, the onLoad handler of the loginReplyXML object is called. You must define the loginReplyXML function, which is called when the onLoad handler triggers, so it can process the loginreply element.

NOTE : This function must always be on the frame that contains the ActionScript for the login button.

If the login is successful, the SWF file progresses to the welcome frame label. If the login is not successful, then the playhead moves to the loginfailure frame label. This is processed using a condition and case statement. For more information on case and break statements, see case statement and break statement in the ActionScript 2.0 Language Reference. For more information on conditions, see if statement and else statement in the ActionScript 2.0 Language Reference.

NOTE : This design is only an example, and Macromedia can make no claims about the level of security it provides. If you are implementing a secure password-protected system, make sure you have a good understanding of network security.

Flash Player 8 introduced the onHTTPStatus event handler for the XML class, LoadVars class, and MovieClipLoader class to allow users to access the status code from an HTTP request. This allows developers to determine why a particular load operation may have failed instead of only being able to determine that a load operation already has failed.

The following example shows how you can use the XML class's onHTTPStatus event handler to check whether an XML file successfully downloaded from the server and what the status code returned from the HTTP request was.

Checking HTTP status codes using the XML class:

  1. Create a new Flash document and save it as xmlhttp.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var my_xml:XML = new XML();

    my_xml.ignoreWhite = true;

    my_xml.onHTTPStatus = function(httpStatus:Number) {

    trace("HTTP status is: " + httpStatus);

    };

    my_xml.onLoad = function(success:Boolean) {

    if (success) {

    trace("XML successfully loaded");

    // 0 (No error; parse was completed successfully.)

    trace("XML status is: " + my_xml.status);

    } else {

    trace("unable to load XML");

    }

    };

    my_xml.load("http://www.helpexamples.com/crossdomain.xml");

    The previous code defines a new XML object with the variable name my_xml, defines two event handlers (onHTTPStatus and onLoad), and loads an external XML file. The onLoad event handler checks to see whether the XML file was successfully loaded and if so sends a message to the Output panel as well as traces the XML object's status property. It is important to remember that the onHTTPStatus event listener returns the status code returned from the web server, whereas the XML.status property contains a numeric value that indicates whether the XML object was able to be parsed successfully.

  3. Select Control > Test Movie to test the Flash document.

TIP : The XML.onHTTPStatus event handler is new to Flash Player 8.

WARNING : Don't confuse the HTTP httpStatus codes with the XML class's status property. The onHTTPStatus event handler returns the server's status code from an HTTP request and the status property automatically sets and returns a numeric value that indicates whether an XML document was successfully parsed into an XML object.

CAUTION : If a web server does not return a status code to the Flash Player, the number 0 is returned to the onHTTPStatus event handler.

There are several sample files on your hard disk that load XML into a SWF file at runtime. One sample demonstrates how to create a web log tracker by loading, parsing, and manipulating XML data. You can find the sample source file, xml_blogTracker.fla, in the Samples folder on your hard disk.

 

Using the XMLSocket class

TOP

ActionScript provides a built-in XMLSocket class, which lets you open a continuous connection with a server. A socket connection lets the server publish, or push, information to the client as soon as that information is available. Without a continuous connection, the server must wait for an HTTP request. This open connection removes latency issues and is commonly used for real-time applications such as chats. The data is sent over the socket connection as one string and should be formatted as XML. You can use the XML class to structure the data.

To create a socket connection, you must create a server-side application to wait for the socket connection request and send a response to the SWF file. This type of server-side application can be written in a programming language such as Java.

NOTE : The XMLSocket class cannot tunnel through firewalls automatically because, unlike the Real-Time Messaging Protocol (RTMP), XMLSocket has no HTTP tunneling capability. If you need to use HTTP tunneling, consider using Flash Remoting or Flash Communication Server (which supports RTMP) instead.

You can use the connect() and send() methods of the XMLSocket class to transfer XML to and from a server over a socket connection. The connect() method establishes a socket connection with a web server port. The send() method passes an XML object to the server specified in the socket connection.

When you invoke the connect() method, Flash Player opens a TCP/IP connection to the server and keeps that connection open until one of the following events happens:

  • The close() method of the XMLSocket class is called.

  • No more references to the XMLSocket object exist.

  • Flash Player exits.

  • The connection is broken (for example, the modem disconnects).

The following example creates an XML socket connection and sends data from the XML object myXML. To understand the script, read the commented lines (indicated by the characters //):

// Create XMLSocket object

var theSocket:XMLSocket = new XMLSocket();

// Connect to a site on unused port above 1024 using connect() method.

// Enter localhost or 127.0.0.1 for local testing.

// For live server, enter your domain www.yourdomain.com

theSocket.connect("localhost", 12345);

// displays text regarding connection

theSocket.onConnect = function(myStatus) {

if (myStatus) {

conn_txt.text = "connection successful";

} else {

conn_txt.text = "no connection made";

}

};

// data to send

function sendData() {

var myXML:XML = new XML();

var mySend = myXML.createElement("thenode");

mySend.attributes.myData = "someData";

myXML.appendChild(mySend);

theSocket.send(myXML);

}

// button sends data

sendButton.onRelease = function() {

sendData();

};

// traces data returned from socket connection

theSocket.onData = function(msg:String):Void {

trace(msg);

};

 

Sending messages to and from Flash Player

TOP

To send messages from a SWF file to its host environment (for example, a web browser, a Macromedia Director movie, or the stand-alone Flash Player), you can use the fscommand() function.This function lets you extend your SWF file by using the capabilities of the host. For example, you could pass an fscommand() function to a JavaScript function in an HTML page that opens a new browser window with specific properties.

To control a SWF file in Flash Player from web browser scripting languages such as JavaScript, VBScript, and Microsoft JScript, you can use Flash Player methods--functions that send messages from a host environment to the SWF file. For example, you could have a link in an HTML page that sends your SWF file to a specific frame.

 

Using the fscommand() function

TOP

NOTE : The External API is a replacement for fscommand() in Flash 8 for interoperating with a HTML page or a container application. The External API offers more robust functionality than fscommand() in this situation. For more information, see About the External API.

You use the fscommand() function to send a message to whichever program is hosting Flash Player, such as a web browser.

NOTE : Using the fscommand() to call JavaScript does not work on the Safari or Internet Explorer browsers for the Macintosh.

The fscommand() function has two parameters: command and arguments. To send a message to the stand-alone version of Flash Player, you must use predefined commands and arguments. For example, the following event handler sets the stand-alone player to scale the SWF file to the full monitor screen size when the button is released:

my_btn.onRelease = function() {

fscommand("fullscreen", true);

};

The following table shows the values you can specify for the command and arguments parameters of fscommand() to control the playback and appearance of a SWF file playing in the stand-alone player, including projectors.

NOTE : A projector is a SWF file saved in a format that can run as a stand-alone application--that is, embedding Flash Player with your content in an executable file.

Command

Arguments

Purpose

quit

None

Closes the projector.

fullscreen

true or false

Specifying true sets Flash Player to full-screen mode. Specifying false returns the player to normal menu view.

allowscale

true or false

Specifying false sets the player so that the SWF file is always drawn at its original size and never scaled. Specifying true forces the SWF file to scale to 100% of the player.

showmenu

true or false

Specifying true enables the full set of context menu items. Specifying false dims all the context menu items except Settings and About Flash Player.

exec

Path to application

Executes an application from within the projector.

To use fscommand() to send a message to a scripting language such as JavaScript in a web browser, you can pass any two parameters in the command and arguments parameters. These parameters can be strings or expressions and are used in a JavaScript function that "catches," or handles, the fscommand() function.

An fscommand() function invokes the JavaScript function moviename_DoFSCommand in the HTML page that embeds the SWF file, where moviename is the name of Flash Player as assigned by the name attribute of the embed tag or the id attribute of the object tag. If the SWF file is assigned the name myMovie, the JavaScript function invoked is myMovie_DoFSCommand.

To use fscommand() to open a message box from a SWF file in the HTML page through JavaScript:

  1. Create a new FLA file, and save it as myMovie.fla.

  2. Drag two instances of the Button component to the Stage and give them the instance names window_btn and alert_btn, respectively, and the labels Open Window and Alert.

  3. Insert a new layer on the Timeline, and rename it Actions.

  4. Select Frame 1 of the Actions layer, and add the following ActionScript in the Actions panel:

    window_btn.onRelease = function() {

    fscommand("popup", "http://www.macromedia.com/");

    };

    alert_btn.onRelease = function() {

    fscommand("alert", "You clicked the button.");

    };

  5. Select File > Publish Settings, and make sure that Flash with FSCommand is selected in the Template menu on the HTML tab.

  6. Select File > Publish to generate the SWF and HTML files.

  7. In an HTML or text editor, open the HTML file that was generated in step 6 and examine the code. When you published your SWF file using the Flash with FSCommand template on the HTML tab of the Publish Settings dialog box, some additional code was inserted in the HTML file. The SWF file's NAME and ID attributes are the filename. For example, for the file myMovie.fla, the attributes would be set to myMovie.

  8. In the HTML file, add the following JavaScript code where the document says // Place your code here.:

    if (command == "alert") {

    alert(args);

    } else if (command == "popup") {

    window.open(args, "mmwin", "width=500,height=300");

    }

    (For more information about publishing, see Publishing in Using Flash.)

    Alternatively, for Microsoft Internet Explorer applications, you can attach an event handler directly in the <SCRIPT> tag, as shown in this example:

    <script Language="JavaScript" event="FSCommand (command, args)" for="theMovie">

    ...

    </script>

  9. Save and close the HTML file.

    When you're editing HTML files outside of Flash in this way, remember that you must deselect the HTML check box in File > Publish Settings, or your HTML code is overwritten by Flash when you republish.

  10. In a web browser, open the HTML file to view it. Click the Open Window button; a window is opened to the Macromedia website. Click the Alert button; an alert window appears.

The fscommand() function can send messages to Macromedia Director that are interpreted by Lingo as strings, events, or executable Lingo code. If the message is a string or an event, you must write the Lingo code to receive it from the fscommand() function and carry out an action in Director. For more information,

 

About using JavaScript to control Flash applications

TOP

Flash Player 6 (6.0.40.0) and later versions support certain JavaScript methods that are specific to Flash applications, as well as FSCommand, in Netscape 6.2 and later. Earlier versions do not support these JavaScript methods and FSCommand in Netscape 6.2 or later. For more information, see the Macromedia Support Center article, "Scripting With Flash," at www.macromedia.com/support/flash/publishexport/scriptingwithflash/.

For Netscape 6.2 and later, you do not need to set the swliveconnect attribute to true. However, setting swLiveConnect to true has no adverse effects on your SWF file. For more information,see the swLiveConnect attribute in Parameters and attributes in Using Flash.

 

About Flash Player methods

TOP

You can use Flash Player methods to control a SWF file in Flash Player from web-browser scripting languages such as JavaScript and VBScript. As with other methods, you can use Flash Player methods to send calls to SWF files from a scripting environment other than ActionScript. Each method has a name, and most methods take parameters. A parameter specifies a value upon which the method operates. The calculation performed by some methods returns a value that can be used by the scripting environment.

Two technologies enable communication between the browser and Flash Player: LiveConnect (Netscape Navigator 3.0 or later on Windows 95/98/2000/NT/XP or Power Macintosh) and ActiveX (Internet Explorer 3.0 and later on Windows 95/98/2000/NT/XP). Although the techniques for scripting are similar for all browsers and languages, there are additional properties and events available for use with ActiveX controls.

 

About the External API

TOP

The ExternalInterface class is also called the External API, which is a new subsystem that lets you easily communicate from ActionScript and the Flash Player container to an HTML page with JavaScript or to a desktop application that embeds Flash Player.

NOTE : This functionality replaces the older fscommand() function for interoperating with a HTML page or a container application. The External API offers more robust functionality than fscommand() in this situation. For more information, see About the External API.

The ExternalInterface class is available only under the following circumstances:

  • In all supported versions of Internet Explorer for Windows (5.0 and later).

  • In an embedded custom ActiveX container, such as a desktop application embedding the Flash Player ActiveX control.

  • In any browser that supports the NPRuntime interface (which currently includes the following browsers:

  • Firefox 1.0 and later

  • Mozilla 1.7.5 and later

  • Netscape 8.0 and later

  • Safari 1.3 and later.

In all other situations, the ExternalInterface.available property returns false.

From ActionScript, you can call a JavaScript function on the HTML page. The External API offers the following improved functionality compared with fscommand():

  • You can use any JavaScript function, not only the functions that you can use with fscommand function.

  • You can pass any number of arguments, with any names; you aren't limited to passing a command and arguments.

  • You can pass various data types (such as Boolean, Number, and String); you are no longer limited to String parameters.

  • You can now receive the value of a call, and that value returns immediately to ActionScript (as the return value of the call you make).

You can call an ActionScript function from JavaScript on an HTML page. For more information, see ExternalInterface (flash.external.ExternalInterface). For more information on local file security, see About local file security and Flash Player.
 

Creating interaction with the External API

TOP

You can create interaction between the browser and a SWF file that's embedded on a web page. The following procedure sends text to the HTML page that contains the SWF file, and the HTML sends a message back to the SWF file at runtime.

To create the Flash application:

  1. Create a new Flash document and save it as extint.fla.

  2. Drag two TextInput components onto the Stage and give them instance names of in_ti and out_ti.

  3. Drag a Label component onto the Stage, assign it an instance name of out_lbl, position it above the out_ti TextInput instance, and set the text property in the Parameters tab of the Property inspector to Sending to JS:.

  4. Drag a Button component onto the Stage, position it next to the out_lbl label, and give it an instance name of send_button.

  5. Drag a Label component onto the Stage, assign it an instance name of in_lbl, position it above the in_ti TextInput instance, and set its text property in the Parameters tab to Receiving from JS:.

  6. Add the following ActionScript to Frame 1 of the main Timeline:

    import flash.external.ExternalInterface;

    ExternalInterface.addCallback("asFunc", this, asFunc);

    function asFunc(str:String):Void {

    in_ti.text = "JS > Hello " + str;

    }

    send_button.addEventListener("click", clickListener);

    function clickListener(eventObj:Object):Void {

    trace("click > " + out_ti.text);

    ExternalInterface.call("jsFunc", out_ti.text);

    }

    The previous code is split into three sections. The first section imports the ExternalInterface class so you don't have to use its fully qualified class name. The second section of code defines a callback function, asFunc(), which is called from JavaScript in an HTML document created in an upcoming example. This function sets the text within a TextInput component on the Stage. The third section of code defines a function and assigns it as an event listener for when the user clicks the Button component instance on the Stage. Whenever the button is clicked, the SWF file calls the jsFunc() JavaScript function in the HTML page and passes the text property of the out_ti text input instance.

  7. Select File > Publish Settings and then select the Formats tab and make sure that Flash and HTML are both selected.

  8. Click Publish to create the HTML and SWF files.

When you're finished, go on to the next procedure to create the container for the SWF file.

Before you can test the previous Flash document, you need to modify the generated HTML code and add some additional HTML and JavaScript. The following procedure modifies the HTML container for the SWF file so the two files can interact when they run in a browser.

To create the HTML container for the SWF file:

  1. Complete the previous procedure.

  2. Open the extint.html file that Flash creates when you publish the application.

    It's in the same folder as the Flash document.

  3. Add the following JavaScript code between the opening and closing head tags:

    <script language="JavaScript">

    <!--

    function thisMovie(movieName) {

    var isIE = navigator.appName.indexOf("Microsoft") != -1;

    return (isIE) ? window[movieName] : document[movieName];

    }

    function makeCall(str) {

    thisMovie("extint").asFunc(str);

    }

    function jsFunc(str) {

    document.inForm.inField.value = "AS > Hello " + str;

    }

    // -->

    </script>

    This JavaScript code defines three methods. The first method returns a reference to the embedded SWF file based on whether the user's browser is Microsoft Internet Explorer (IE) or a Mozilla browser. The second function, makeCall(), calls the asFunc() method that you defined within the Flash document in the previous example. The "extint" parameter in the thisMovie() function call refers to the object ID and embed name of the embedded SWF file. If you saved your Flash document with a different name, you need to change this string to match the values in the object and embed tags. The third function, jsFunc(), sets the value of the inField text field in the HTML document. This function is called from the Flash document when a user clicks the

    send_button Button component.

  4. Add the following HTML code before the closing </body> tag:

    <form name="outForm" method="POST" action="javascript:makeCall(document.outForm.outField.value);">

    Sending to AS:<br />

    <input type="text" name="outField" value="" /><br />

    <input type="submit" value="Send" />

    </form>

    <form name="inForm" method="POST" action="">

    Receiving from AS:<br />

    <input type="text" name="inField">

    </form>

    This HTML code creates two HTML forms similar to the forms created in the Flash environment in the previous exercise. The first form submits the value of the outField text field to the makeCall() JavaScript function defined in an earlier step. The second form is used to display a value that gets sent from the SWF file when the user clicks the send_button instance.

  5. Save the HTML document and upload both the HTML and SWF files to a web server.

  6. View the HTML file in a web browser, enter a string in the out_ti TextInput instance, and click the Send button.

    Flash calls the jsFunc() JavaScript function and passes the contents of the out_ti text field, which displays the contents in the HTML form inForm inField input text field.

  7. Type a value into the outField HTML text field and click the Send button.

Flash calls the SWF file's asFunc() function, which displays the string in the in_ti TextInput instance.

NOTE : Avoid using other methods of accessing the plug-in object, such as document.getElementById("pluginName") or document.all.pluginName, because these other methods do not work consistently across all browsers.
 

Controlling Flash Video with the External API  
The following procedure shows you how to control Flash Video (FLV) files using controls in an HTML page and displays information about the video in an HTML text field. This procedure uses the External API to achieve this functionality.

To build a Flash application using the External API:

  1. Create a new Flash document and save it as video.fla.
  2. Add a new video symbol to the library by selecting New Video from the pop-up menu in the Library panel.
  3. Drag the video symbol to the Stage and give it an instance name of selected_video.
  4. Select the selected_video instance and then the Property inspector to resize the instance to 320 pixels wide by 240 pixels high.
  5. Set both the x and y coordinates for the video's position to 0.
  6. Select the Stage and use the Property inspector to resize its dimensions to 320 pixels by 240 pixels.

    Now the Stage matches the dimensions of the video instance.

  7. Add the following ActionScript to Frame 1 of the main Timeline:

    import flash.external.ExternalInterface;

    /* Register playVideo() and pauseResume() so that it is possible

    to call them from JavaScript in the container HTML page. */

    ExternalInterface.addCallback("playVideo", null, playVideo);

    ExternalInterface.addCallback("pauseResume", null, pauseResume);

    /* The video requires a NetConnection and NetStream object. */

    var server_nc:NetConnection = new NetConnection();

    server_nc.connect(null);var video_ns:NetStream = new NetStream(server_nc);

    /* Attach the NetStream object to the Video object on Stage so

    that the NetStream data is displayed in the Video object. */

    selected_video.attachVideo(video_ns);

    /* The onStatus() method is called automatically when the status of

    the NetStream object is updated (the video starts playing, for example).

    When that occurs, send the value of the code property to the HTML page by

    calling the JavaScript updateStatus() function via ExternalInterface. */

    video_ns.onStatus = function(obj:Object):Void {

    ExternalInterface.call("updateStatus", " " + obj.code);

    };

    function playVideo(url:String):Void {

    video_ns.play(url);

    }

    function pauseResume():Void {

    video_ns.pause();

    }

    The first part of this ActionScript code defines two ExternalInterface callback functions, playVideo() and pauseResume(). These functions are called from the JavaScript in the next procedure.

     The second part of the code creates a new NetConnection and NetStream object, which you use with the video instance to dynamically play back FLV files.

    The code in the next procedure defines an onStatus event handler for the video_ns NetStream object. Whenever the NetStream object changes its status, Flash uses the ExternalInterface.call() method to trigger the custom JavaScript function, updateStatus(). The final two functions, playVideo() and pauseResume(), control the playback of the video instance on the Stage. Both of these functions are called from JavaScript written in the following procedure.

  8. Save the Flash document.
  9. Select File > Publish Settings and then select the Formats tab, and make sure that HTML and Flash are both selected.
  10. Click Publish to publish the SWF and HTML files to your hard disk.

When you're finished, go on to the next procedure to create the container for the SWF file.

In the following procedure, you modify the HTML code generated by Flash in the previous procedure. This procedure creates the JavaScript and HTML required to make the FLV files play back

within the SWF file.

To create the container for the SWF file:

  1. Complete the previous procedure.
  2. Open the video.html document that you published in the last step of the previous procedure.
  3. Modify the existing code so that it matches the following code:

    NOTE : Review the code comments in the following example. A code overview follows this code example.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

    <head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <title>ExternalInterface</title>

    <script language="JavaScript">

    // Use a variable to reference the embedded SWF file.

    var flashVideoPlayer;
     

    /* When the HTML page loads (through the onLoad event of the <body> tag), it calls the initialize() function. */

    function initialize() {

    /* Check whether the browser is IE. If so, flashVideoPlayer is

    window.videoPlayer. Otherwise, it's document.videoPlayer. The

    videoPlayer is the ID assigned to the <object> and <embed> tags. */

    var isIE = navigator.appName.indexOf("Microsoft") != -1;

    flashVideoPlayer = (isIE) ? window['videoPlayer'] : document['videoPlayer'];

    }

    /* When the user clicks the play button in the form, update the videoStatus text area, and call the playVideo() function within the SWF file, passing it the URL of the FLV file. */

    function callFlashPlayVideo() {

    var comboBox = document.forms['videoForm'].videos;

    var video = comboBox.options[comboBox.selectedIndex].value;

    updateStatus("____" + video + "____");

    flashVideoPlayer.playVideo("http://www.helpexamples.com/flash/video/" + video);

    }

    // Call the pauseResume() function within the SWF file.

    function callFlashPlayPauseVideo() {

    flashVideoPlayer.pauseResume();

    }

    /* The updateStatus() function is called from the SWF file from the onStatus() method of the NetStream object. */

    function updateStatus(message) {

    document.forms['videoForm'].videoStatus.value += message + "\n";

    }

    </script>

    </head>

    <body bgcolor="#ffffff" onLoad="initialize();">

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"

    codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="320" height="240" id="videoPlayer" align="middle">

    <param name="allowScriptAccess" value="sameDomain" />

    <param name="movie" value="video.swf" />

    <param name="quality" value="high" />

    <param name="bgcolor" value="#ffffff" />

    <embed src="video.swf" quality="high" bgcolor="#ffffff" width="320" height="240" name="videoPlayer" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave

    flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />

    </object>

    <form name="videoForm">

    Select a video:<br />

    <select name="videos">

    <option value="lights_long.flv">lights_long.flv</option>

    <option value="clouds.flv">clouds.flv</option>

    <option value="typing_long.flv">typing_long.flv</option>

    <option value="water.flv">water.flv</option>

    </select>

    <input type="button" name="selectVideo" value="play" onClick="callFlashPlayVideo();" />

    <br /><br />

    Playback <input type="button" name="playPause" value="play/pause" onClick="callFlashPlayPauseVideo();" />

    <br /><br />

    Video status messages <br />

    <textarea name="videoStatus" cols="50" rows="10"></textarea>

    </form>

    </body>

    </html>

    This HTML code defines four JavaScript functions: initialize(), callFlashPlayVideo(), callFlashPlayPauseVideo(), and updateStatus(). The initialize() function is called within the body tag in the onLoad event. Both the callFlashPlayVideo() and callFlashPlayPauseVideo() functions are called when the user clicks on either the play button or play/pause button within the HTML document, and trigger the playVideo() and pauseResume() functions in the SWF file.

    The final function, updateStatus(), gets called by the SWF file whenever the video_ns NetStream object's onStatus event handler is triggered. This HTML code also defines a form that has a combo box of videos that the user can choose from. Whenever the user selects a video and clicks the play button, the callFlashPlayVideo() JavaScript function is called, which then calls the playVideo() function within the SWF file. This function passes the URL of the SWF file to load into the video instance. As the video plays back and the NetStream object's status changes, the contents of the HTML text area on the Stage are updated.

  4. Save your changes to the HTML document, and then upload both the HTML and SWF files to a website.
  5. Open the remote video.html document from the website, select a video from the combo box, and click the play button.

Flash plays the selected FLV file and updates the contents of the videoStatus text area within the HTML document.

 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash