Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
104
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 25

fileTransferProgressBar.setProgress(bytesLoaded, bytesTotal);

}

fileRefListener.onComplete = function(file:FileReference)

{

feedbackField.text = “Upload complete.”; fileTransferProgressBar._visible = false;

}

fileRefListener.onHTTPError = function (file:FileReference)

{

feedbackField.text = “Upload failed - network error.”; fileTransferProgressBar._visible = false;

}

fileRefListener.onIOError = function (file:FileReference)

{

feedbackField.text = “Upload failed - disk error.”; fileTransferProgressBar._visible = false;

}

fileRefListener.onSecurityError = function (file:FileReference)

{

feedbackField.text = “Upload failed - security/permissions error.”; fileTransferProgressBar._visible = false;

}

eventHandler.click = function()

{

fileRef.addListener(fileRefListener);

fileRef.browse(fileTypes);

}

8.Save the file, return to the Macromedia Flash project file, and select Control Test Movie.

How It Works

First, the relevant classes are imported, to make referring to component names and class names a bit easier:

import mx.controls.Button; import mx.controls.ProgressBar; import flash.net.FileReference;

Next, you initialize a few arrays. Even though you can download multiple files, you only use one instance of the FileReference class. If you wanted to be able to download several files at once, you would need one instance for each simultaneous connection:

var eventHandler:Object = new Object(); var fileRefListener:Object = new Object();

var fileRef:FileReference = new FileReference();

In order for the file selection dialog box to work, the list of accepted file types is given. Any files with a file type not listed here are not clickable. The description is not used with MacOS but is used with Windows to provide a drop-down menu of file type filters:

648

Uploading and Downloading Files

var fileTypes:Array = new Array();

var imageTypes:Object = new Object();

imageTypes.description = “Images (*.jpg, *.jpeg, *.gif, *.png)”; imageTypes.extension = “*.jpg; *.jpeg; *.gif; *.png”; fileTypes.push(imageTypes);

var htmlTypes:Object = new Object(); htmlTypes.description = “HTML (*.html, *.htm)”; htmlTypes.extension = “*.html; *.png”; fileTypes.push(htmlTypes);

The user interface is set up, which involves placing the Label, TextInput, Button, and ProgressBar components on the stage:

setupInterface();

function setupInterface()

{

this.createClassObject(Button, “openWindowButton”, ; this.getNextHighestDepth(), {_x:10, _y:20});

openWindowButton.label = “Upload”; openWindowButton.addEventListener(“click”, eventHandler);

this.createClassObject(ProgressBar, “fileTransferProgressBar”, ; this.getNextHighestDepth());

fileTransferProgressBar._x = 120; fileTransferProgressBar._y = 20; fileTransferProgressBar.mode = “manual”; fileTransferProgressBar.label = “Uploaded %3%%”; fileTransferProgressBar._visible = false;

this.createTextField(“feedbackField”, this.getNextHighestDepth(), 10, 50, 400,

30);

}

Next, you define event handlers for the FileReference instance. The onSelect event is called when the user has selected a file to upload. This is where the upload() method is called to start sending the file to the server upload script:

fileRefListener.onSelect = function(file:FileReference)

{

feedbackField.text = “File selected: “ + file.name; file.upload(“http://www.yourdomain.com/yourUploadHandlerScript.cfm”)

}

Startup code is placed within the onOpen event handler:

fileRefListener.onOpen = function(file:FileReference)

{

feedbackField.text = “Starting file upload.”; fileTransferProgressBar._visible = true;

}

649

Chapter 25

The onProgress event updates the progress bar:

fileRefListener.onProgress = function(file:FileReference, bytesLoaded:Number, ; bytesTotal:Number)

{

feedbackField.text = “Upload in progress.”; fileTransferProgressBar.setProgress(bytesLoaded, bytesTotal);

}

The onComplete event indicates the successful completion of the file upload:

fileRefListener.onComplete = function(file:FileReference)

{

feedbackField.text = “Upload complete.”; fileTransferProgressBar._visible = false;

}

The onHTTPError event handler reports an aborted transfer due to a network problem:

fileRefListener.onHTTPError = function (file:FileReference)

{

feedbackField.text = “Upload failed - network error.”; fileTransferProgressBar._visible = false;

}

The onIOError event handler reports an aborted transfer due to a disk problem:

fileRefListener.onIOError = function (file:FileReference)

{

feedbackField.text = “Upload failed - disk error.”; fileTransferProgressBar._visible = false;

}

The onSecurityError event handler reports an aborted transfer due to a security issue, such as incorrect permissions set on the server’s upload directory:

fileRefListener.onSecurityError = function (file:FileReference)

{

feedbackField.text = “Upload failed - security/permissions error.”; fileTransferProgressBar._visible = false;

}

Finally, clicking the Upload button calls the browse() method to prompt the user to select a file:

eventHandler.click = function()

{

fileRef.addListener(fileRefListener);

fileRef.browse(fileTypes);

}

650

Uploading and Downloading Files

Summar y

This chapter introduced the FileReference class for uploading and downloading files. Some of the things you learned include the following:

The FileReference class gives you the capability to control how users download external files to their local machines and how they upload files to the server.

By making use of the FileReference events onHTTPError, onIOError, and onSecurityError, you can gracefully respond to problems with file uploads or downloads.

Uploading files requires a server-side upload script that is dependent on the server software used.

Exercise

1.Modify the Download Files Try It Out exercise so that when you pull the network plug in the middle of a transfer, it waits for 30 seconds, and then tries again. After three attempts, it should alert the user of the failure.

651

26

Communicating between the Flash Plug-in and the Operating System

The term Flash wrapper is used loosely to describe any environment that’s capable of displaying an

.swf file. The wrapper defines how Flash works with its surroundings. The Macromedia Flash browser plug-in, for example, is a Flash wrapper. A plug-in permits only limited access to the system. The Macromedia Flash Projector wrapper allows for a little bit more communication. Third-party wrappers such as Northcode (www.northcode.com) provide robust ActionScript object additions, allowing the development of sophisticated applications capable of interacting with the system in a much more unrestricted manner. With Northcode, you can save text files, make screen grabs, play external video formats, open web pages directly within Flash, and much more. Macromedia also provides an SDK (Software Development Kit) to enable anyone to include .swf files within larger applications built with languages such as Visual Basic.

One aspect of the Flash player that can help you create a more thorough and stable application is Flash’s capability to obtain information about the system in which it is running. There are times when you may be targeting an array of devices, operating systems, and hardware where the capability to access different aspects of multimedia such as sound, video, and input devices varies from channel to channel. Ascertaining the existence of these system attributes enables you to change the behavior of your application so that it performs at its best, no matter which system it resides on.

Using the System Object

to Retrieve System Information

The System object is a global object that holds properties about the system, player settings, and plugin version. It also has a few useful functions for setting security parameters for the application.

In the following Try It Out, you use a simple loop to display the values available within the System object. You don’t need to do this every time you want to fetch a System value. It’s just a simple way to display all the values available.

Chapter 26

Try It Out

Query the System Object

1.Open a new .fla.

2.Select the first frame in the Timeline panel, open the Actions panel, and enter the following code:

function traceObject (obj, indent) { if (indent == undefined) {

indent = “”;

}

for (var i in obj) {

trace (indent + i + “ = “ + obj[i]); if (typeof (obj[i]) == “object”) {

var newIndent = indent + “ “; traceObject (obj[i], newIndent);

}

}

}

traceObject (System);

3.Test the query. The System object is outlined in the output window, similar to the following:

IME [object Object] setClipboard [type Function] security [object Object]

sandboxType localTrusted escapeDomain [type Function] chooseLocalSwfPath [type Function] loadPolicyFile [type Function] allowInsecureDomain [type Function] allowDomain [type Function]

exactSettings true showSettings [type Function] Product [type Function] capabilities [object Object]

hasIME true language en os Windows XP

manufacturer Macromedia Windows windowlessDisable false localFileReadDisable false avHardwareDisable false playerType External

isDebugger true hasScreenBroadcast false hasScreenPlayback true hasPrinting true hasEmbeddedVideo true hasStreamingVideo true hasStreamingAudio true version WIN 8,0,0,450 serverString

A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&SB=f&DEB=t&V=WIN%208%2C0%2C0%2C4

50&M=Macromedia%20Windows&R=1400x1050&DP=72&COL=color&AR=1.0&OS=Windows%20XP&L=en&I

ME=t&PT=External&AVD=f&LFD=f&WD=f

654

Communicating between the Flash Plug-in and the Operating System

hasAudio true hasMP3 true hasAudioEncoder true hasVideoEncoder true

screenResolutionX 1400 screenResolutionY 1050 screenDPI 72 screenColor color pixelAspectRatio 1 hasAccessibility false

How It Works

The System object is exposed using a simple recursive function. A recursive function is a function that has the capability to call itself or other objects with the same function.

One helpful value within the System object is the player version value found within the capabilities object. If an application required the plug-in version it is running within, the code System.capabilties

.version, in this case, would return 8,0,0,450. The property returns whatever player version you have installed. This is useful for redirecting users to different content or a new SWF, or alerting the user that his current player needs to be upgraded or changed.

System Object Limitations among Player Versions

Different versions of the Flash player have different properties available within the System object. Flash 5 has no System object, and Flash 6 has a limited System object. It is always wise to check for the existence of a property as you attempt to use it. This goes for any property or variable in your code, but is especially so with the System object, which can affect how the entire application performs.

The setClipBoard Method

The setClipBoard method, which you used in the preceding Try It Out, enables you to send Strings to the clipboard. However, there is no way to retrieve the contents of the clipboard from your SWF. It does enable you to offer other programs on the system quick access to content created within Flash. You might send the results of a complex math calculation to the clipboard and instruct the user to paste it into Excel, for example. The clipboard activity is one-directional; Flash can only send information to the clipboard. Other applications need some method of retrieving it, or instructions need to be provided to the user. Flash cannot obtain the contents of the clipboard via ActionScript.

The syntax is as follows:

System.setClipBoard(str:String);

The str parameter is simply a String. Although some system limitations may exist for specific operating systems, Flash does not limit the size of the String to be written to the clipboard.

When you send data to the clipboard, the clipboard is automatically cleared. This can be a useful feature when you’d like selectable text, but you want to disallow the pasting of the text.

655

Chapter 26

Projectors, Flash Executables,

and Other Executables

Flash is primarily a web platform, with users accessing SWF content via http pages. However, Flash can be packaged within executable files, which are essentially standalone Flash players that have SWF content.

To create a Flash executable, you simply select Flash projector output in the Publish Settings options.

Although the projector output from Flash has no options, you can do a few things with the executable file with ActionScript using fscommand. ActionScript uses the FSCommand object to communicate with the system. The available fscommands are listed in the “Using fscommand to Call Projector Functions” section later in this chapter.

fscommand is used with executables to specify quit commands and other attributes. It can be used to communicate with JavaScript as well. (The fscommand-to-JavaScript communication is described in Chapter 23.) fscommand is also utilized when Flash is used in conjunction with Macromedia Director files. A separate object called fcommand2 is used specifically for Flash lite to access cell phone functions.

Limitations

It should be noted that the Flash fscommand does not support a save method for text files.

The Flash projector no longer launches .bat files. Flash no longer opens .pdf files via fscommand. FSCommand was able to open these two file types in Flash 6, which implemented the fscommand folder.

The fscommand folder must reside in the same directory as your Flash executable file. You can place

.exe files within a folder named fscommand.

FSCommands are most commonly used to access commands within a Flash projector.

Using fscommand to Call Projector Functions

Calling an fscommand method is simple from anywhere in your application. Here’s the syntax:

fscommand(command,parm);

command is a String, the name of the command you want to execute; parm is also a String — the required parameter for the command. The available command and parm values are described in the following table:

Command

Parameter

Description

 

 

 

quit

None

Closes the Projector file. This command is usually

 

 

honored by third-party wrappers as well.

fullscreen

String representing a

If the parameter is set to true, the application is

 

Boolean value, true or

maximized to the full screen size. If the parameter

 

false

is false, and the application is in fullscreen

 

 

mode, the application will be unminimized.

 

 

 

656

Communicating between the Flash Plug-in and the Operating System

Command

Parameter

Description

 

 

 

allowscale

String representing a

If true, the movie is scaled to 100% of the

 

Boolean value, true or

application window’s screen size. If false, the

 

false

canvas is enlarged, but the items remain at the

 

 

size at which they were authored to.

showmenu

String representing a

If true, the Flash player’s context menu shows

 

Boolean value, true or

a full set of options. If false, the Flash player’s

 

false

context menu has only Settings and About

 

 

options. There is no way to fully remove the

 

 

context menu.

exec

String specifying

Launches an executable file.

 

the name of an

 

 

executable file.

 

trapallkeys

String representing a

If true, the onClipEvent(keyDown/keyUp)

 

Boolean value, true or

event handler fires when any key is pressed.

 

false

 

The external API has taken on many of the aspects of fscommand, and some third-party wrappers and JavaScript communications require the external API rather than fscommand.

When using the exec command via fscommand, you must create a special folder called fscommand. All executable files you want to launch via your application must reside in that folder.

The following example shows you how and where the folder must be created to work with your projector to launch applications.

Try It Out

Launch a Program Using fscommand

This example assumes a PC platform. To use a Mac, make the appropriate program string name changes and choose a program of your choice to use.

At the time of this writing, performance of a PC Macromedia Projector file under WINE for Linux was unknown. It may be that some things, such as fullscreen, might not work as expected.

1.Open a new FLA, and save it as fscommandExec.fla in your workspace folder.

2.Open the User Interface section of the Components panel and drag an instance of the Component button onto the stage.

3.Open the Parameters tab in the Properties panel and change the Label parameter from Button to Open Calculator.

4.In the Properties panel, change the Instance name of the button component to myButton. (The Instance name field is just below the word Component on the left side of the panel.)

5.Select the first frame in the timeline and enter the following code:

myButton.onRelease = function(){ fscommand(“exec”,”calc.exe”);

}

657