by Jeff Swartz

Jeff Swartz


10 October 2011

Prerequisite knowledge

General experience of building applications
with Flex Builder or the Flex SDK is
suggested. For more details on getting
started with this quick start, refer to
Building the Quick Start sample
applications with Flex
Required products

Sample files

User level

The PhotoUpload sample application, shown in Figure 1, demonstrates the following features of working with files in Adobe AIR:
  • Setting up a File object to point to a file path.
  • Converting an image to JPEG binary data and writing the data to a file.
  • Uploading files to a server
JPEG file uploader
Figure 1. This sample application enables you to upload JPEG files.
Note: This is a sample application provided, as is, for instructional purposes.
This sample application includes the following files:
  • PhotoUpload.mxml: The main application file in MXML for Flex; includes the code discussed in this article
  • PhotoUpload-app.xml: The AIR application descriptor file
  • A utility class used by the JPGEncoder class
  • A utility class used by the JPGEncoder class
  • A class used to upload files to a web server
  • index.php: A file to include in the http://localhost/PhotoSyncUpload/ folder of your PHP-enabled web server
  • Sample AIR icon files
Note: This is a sample application uses the JPGEncoder and classes, which are published at the ActionScript 3.0 Corelib project.
This application requires you to have a webcam installed, and you must have access to a PHP-enabled web server.
Important: The application descriptor file, FileCompressionTool-app.xml, uses the AIR 3.0 namespace. To modify and repackage this application, you need to download and use AIR 3 SDK along with Flash Builder 4.5.

Testing the application

This sample application lets you capture images from a web cam and upload the captured images (stored as JPEG files) to a web server.
Before running the application (PhotoUploadFlex.air), install the index.php file (included with the source files in the PHP directory) in the http://localhost/PhotoSyncUpload/ folder of your PHP-enabled web server. Also, make sure that a webcam is installed on your computer.
To test the application:
  1. Install the application (by double-clicking the provided AIR file), and run it.
  2. Point your webcam to something that you want to take a picture of.
  3. Click the Preview button. Then click the Save button to save the image.
  4. Repeat this step to save multiple images.
  5. Click the Upload button to upload the files to your web server.

Understanding the code

Note: This article does not describe all of the Flex components used in the MXML code for the file. For more information, see the ActionScript 3 Reference for the Adobe Flash Platform.
Previewing the webcam image
The shoot() method calls the flasher() method which simulates a camera flash by quickly rendering an opaque white NativeWindow to fill the screen:
private function flasher():void { var windowInitOpts:NativeWindowInitOptions = new NativeWindowInitOptions(); windowInitOpts.systemChrome = NativeWindowSystemChrome.NONE; windowInitOpts.type = NativeWindowType.LIGHTWEIGHT; var flashCube:NativeWindow = new NativeWindow(windowInitOpts); flashCube.x = 0; flashCube.y = 0; flashCube.width = Capabilities.screenResolutionX; flashCube.height = Capabilities.screenResolutionY; flashCube.visible = true; setTimeout(closeFlash, 100, flashCube); } private function closeFlash(flashCube:NativeWindow):void { flashCube.close() }
The shoot() method then captures the image in the video VideoDisplay component to a BitmapData object and writes that BitmapData to the shot Image component (by setting the source property of the Image component):
bmd = new BitmapData(video.width, video.height); bmd.draw(video); var bmp:Bitmap = new Bitmap(bmd); bmp.x = (stage.stageWidth - bmp.width)/2 shot.source = bmp;
Saving a file
The save() method sets up a FileStream object to write the image data to a file. The image data is converted to a ByteArray containing JPEG-encoded data by calling the encode() method of a JPEGEncoder object:
private function save():void { file = File.applicationStorageDirectory; file = file.resolvePath("images/" + new Date().time.toString() + ".jpg"); stream = new FileStream;, FileMode.WRITE); var data:ByteArray = getJPEG(bmd); stream.writeBytes(data, 0, data.length); stream.close(); } private function getJPEG(bmd:BitmapData):ByteArray { var jpg:JPGEncoder = new JPGEncoder(); return jpg.encode(bmd); }
Note that the file object points to a file in the images subdirectory of the application resource directory, and the name of the file is based on a timestamp provided by a Date object's time property:
file = File.applicationStorageDirectory; file = file.resolvePath("images/" + new Date().time.toString() + ".jpg");
Uploading files to a web server
The Uploader class contains code that uploads files to a web server. You add a file to the list of files to upload by calling the addFile() method of an Uploader object, passing a File object to the method:
for (var i:uint = 0; i < files.length; i++) { file = files[i]; if (!file.isDirectory) { uploader.addFile(file); } }
You register event listeners for the complete and progress events of the Uploader object and then call its start() method, which uploads the files to the URL passed as a parameter:
uploader.addEventListener(Event.COMPLETE, uploadCompleteHandler); uploader.addEventListener(ProgressEvent.PROGRESS, progressHandler); uploader.start(UPLOAD_URL + "/index.php");
The Uploader object uploads the files one at a time by calling its upload() method, passing the File object as a parameter:
private function uploadFile(file:File):void { var urlRequest:URLRequest = new URLRequest(url); urlRequest.method = URLRequestMethod.POST; file.addEventListener(ProgressEvent.PROGRESS, uploadProgress); file.addEventListener(Event.COMPLETE, uploadComplete); file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA , uploadServerData); file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, uploadError); file.addEventListener(HTTPStatusEvent.HTTP_STATUS, uploadError); file.addEventListener(IOErrorEvent.IO_ERROR, uploadError); file.upload(urlRequest, "uploadfile"); }
The upload() method of the File object uploads the file to the given URL (specified as a URLRequest object):
The PHP page you posted on your web server recognizes the string as its cue to accept the file provided as POST data as a file to be uploaded (and saved on the web server, in an uploaded subdirectory).
The user can preview the web page containing the uploaded files by clicking the View in Browser button, which calls the viewHTML() method. This method calls the navigateToURL() function, which opens a web page in the default system web browser:
private function viewHTML():void { var urlReq:URLRequest = new URLRequest(UPLOAD_URL + "/uploaded"); navigateToURL(urlReq); }