Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Adobe AIR Developer Center / AIR Quick Starts for HTML/JavaScript developers /

Building a JPEG file uploader

by Jeff Swartz

Jeff Swartz  Adobe

Modified

9 June 2010

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
Adobe AIR

Requirements

Prerequisite knowledge

General experience building HTML-based applications is suggested. For more details on getting started with this Quick Start, refer to Building the Quick Start sample applications with HTML.

 

Additional Requirements

  • Adobe AIR SDK

User level

Intermediate

Required products

  • Adobe AIR

Sample files

  • PhotoUploadHTML.zip
  • PhotoUploadHTML.air

Note: This application requires you to have a webcam installed, and you must have access to a PHP-enabled web server.

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 temporary file
  • Writing data to a file
  • Uploading files to a server
  • Deleting files
  • Responding to the exiting event of the NativeApplication object
  • Accessing an ActionScript class in a SWF file from JavaScript
  • Using advanced runtime classes (Camera, and Video) that are not documented in the JavaScript Language Reference for Adobe AIR.
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:

  • index.html: The main application content; discussed in this article.
  • application.xml: The AIR application descriptor file
  • js/Uploader.js: A JavaScript file containing much of the logic used in the application. Details of the code are discussed in the “Understanding the code” on page 3 section.
  • js/AIRAliases.js: The AIR JavaScript aliases file
  • swf/JPGEncoderLib.swf: A SWF file that contains an ActionScript 3.0 class named JPGEncoder.
  • swf_src/com/adobe/images/swf_src/JPGEncoderLib.as: The ActionScript 3.0 source file used to compile the JPGEncoderLib.swf file. You can use the JPGEncoderLib.swf file provided with this sample. However, for security reasons, it is a good practice to recompile SWF files from the source code when provided from third-party sources.
  • swf_src/com/adobe/images/JPGEncoder.as: A utility class used by the JPGEncoder class. This class is also available at the ActionScript 3.0 Corelib project.
  • BitString.as: A utility class used by the JPGEncoder class. This class is also available at the ActionScript 3.0 Corelib project.
  • PHP/index.php: A file to include in the http://localhost/PhotoSyncUpload/ folder of your PHP-enabled web server.
  • Sample AIR icon files

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.

Photo Uploader uses the JPGEncoder class of a SWF file to convert data to JPEG format. The JPGEncoder class is published at the ActionScript 3.0 Corelib project (located at http://code.google.com/p/as3corelib).

Before running the application (PhotoUploadHTML.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

For more information about using AIR classes, see the Adobe AIR Language Reference for HTML Developers.

Previewing the webcam image

The appInit() method in the Uploader.js file uses two classes that are documented in the ActionScript 3.0 documentation: the Camera class and the Video class. The camera object (an instance of the Camera class) is assigned a webcam on the user’s computer by calling the getCamera() method of the Camera class. If no camera is present, the application notifies the user by calling the alert() function. The video object (an instance of the Video class) is the ActionScript 3.0 display object that is assigned to display the images captured by the camera.

camera = window.runtime.flash.media.Camera.getCamera(); if (camera) { video = new window.runtime.flash.media.Video(); video.attachCamera(camera); camera.addEventListener(air.ActivityEvent.ACTIVITY, setSize); } else { alert("No cameras are available."); }

The setSize() function sets the height and width of the video, and then calls the shoot() function:

function setSize() { video.width = camera.width * 2; video.height = camera.height * 2; shoot(false); }

The shoot() function calls the flasher() function which simulates a camera flash by quickly rendering an opaque white NativeWindow to fill the screen:

function shoot(flash) { if (flash) { flasher(); } bmd = new window.runtime.flash.display.BitmapData(video.width, video.height); bmd.draw(video); saveTemp(); } function flasher() { var windowInitOpts = new air.NativeWindowInitOptions(); windowInitOpts.systemChrome = air.NativeWindowSystemChrome.NONE; windowInitOpts.type = air.NativeWindowType.LIGHTWEIGHT; var flashCube = new air.NativeWindow(windowInitOpts); flashCube.x = 0; flashCube.y = 0; flashCube.width = air.Capabilities.screenResolutionX; flashCube.height = air.Capabilities.screenResolutionY; flashCube.visible = true; setTimeout(closeFlash, 100, flashCube); } function closeFlash(flashCube) { flashCube.close(); }

The flash parameter of the shoot method is set to false when the application first calls the method during the initialization (in the appInit() method).

The shoot() method then captures the image in the video object, saving it to a BitmapData object, bmd. The flash.display.BitmapData class is described in the ActionScript 3.0 documentation.

bmd = new window.runtime.flash.display.BitmapData(video.width, video.height); bmd.draw(video);

Saving a file

When the application initializes and when the user clicks the Preview button, the saveTemp() method saves the image to a JPEG file which is then loaded into the img image.

The application must convert the BitmapData data contained in the bmd object into JPEG format. The JPGEncoder ActionScript 3.0 class, published at the corelib project (located at at http://code.google.com/p/as3corelib) does just that. The JPGEncoderLib.swf file, provided with the source files in the swf directory, contains that JPGEncoder class, and this HTML-based application makes the classes in that SWF file available to JavaScript code by loading the SWF file using the following script tag (in the index.html file):

<script src="swf/JPGEncoderLib.swf" type="application/x-shockwave-flash"></script>

The saveTemp() function saves the JPEG data to a temporary file (which is created by calling air.File.createTempFile()). Data is saved to the file by creating a FileStream object and calling the writeBytes() method of that object. The temp file is then loaded into the img image in the document. The image data is converted to a ByteArray object containing JPEG-encoded data by calling the encode() method of a JPGEncoder object:

function saveTemp() { tempFile = air.File.createTempFile(); temps.push(tempFile); saveJPEG(tempFile); img.src = ""; img = window.document.getElementById("img"); img.src = tempFile.url; img.width = 320; img.height = 240; } function saveJPEG(file) { stream = new air.FileStream(); stream.open(file, air.FileMode.WRITE); var data = getJPEGData(bmd); stream.writeBytes(data, 0, data.length); stream.close(); return file; } function getJPEGData(bmd) { var jpegEncoder = new window.runtime.com.adobe.images.JPGEncoder(); return jpegEncoder.encode(bmd); }

When the user clicks the Save button, the save() method saves the image to a JPEG file in the images subdirectory of the application resource directory. The name of the file is based on a timestamp provided by a Date object’s time property:

function save() { var timestamp = new Date().getTime().toString(); var path = "images/" + timestamp + ".jpg"; file = air.File.applicationStorageDirectory.resolvePath(path); saveJPEG(file); }

Uploading files to a web server

The Uploader.as file contains code that uploads files to a web server. The list of saved files is stored in the files array (an array of File objects). The upload() method looks through the list of files in the images subdirectory of the application storage directory:

function upload() { totalSize = 0; files = new Array(); var dir = air.File.applicationStorageDirectory.resolvePath("images"); var allNodes = dir.getDirectoryListing(); for (var i = 0; i < allNodes.length; i++) { file = allNodes[i]; if (!file.isDirectory) { files.push(file); totalSize += file.size; } } url = UPLOAD_URL uploadedSoFar = 0; uploadNext(); }

The uploadNext() function extracts one File object from the files array, and calls the uploadFile() function, which uploads the file:

function uploadNext() { if (files.length > 0) { currentFile = files.pop(); uploadFile(currentFile); } } function uploadFile(file) { var urlRequest = new air.URLRequest(url); urlRequest.method = air.URLRequestMethod.POST; file.addEventListener(air.ProgressEvent.PROGRESS, uploadProgress); file.addEventListener(air.Event.COMPLETE, uploadComplete); file.addEventListener(air.SecurityErrorEvent.SECURITY_ERROR, uploadError); file.addEventListener(air.HTTPStatusEvent.HTTP_STATUS, uploadError); file.addEventListener(air.IOErrorEvent.IO_ERROR, uploadError); file.upload(urlRequest, "uploadfile"); }

The ploadFile() function sets a number of event listeners for the File object being uploaded:

function uploadProgress(event) { var uploadedAmt = uploadedSoFar + event.bytesLoaded; event.bytesLoaded = uploadedAmt; event.bytesTotal = totalSize; air.trace("Progress", event.bytesLoaded, event.bytesTotal); } function uploadComplete(event) { uploadedSoFar += currentFile.size; var newLocation = currentFile.parent.resolvePath("uploaded/" + currentFile.name); uploadNext(); } function uploadError(event) { var errorStr = event.toString(); air.trace("Error uploading: " + currentFile.nativePath + "\n Message: " + errorStr); }

Note that the uploadComplete() function—the event handler that is called when a file is uploaded—calls the uploadNext() function to upload the next file (if there is one).

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).

Deleting temporary files upon exiting the application

The appInit() function sets up an event listener for the exiting event, which is dispatched by the NativeApplication object when the application exits:

air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, appExiting);

The NativeApplication object dispatches the exiting event when the user closes the main. The appExiting() function handles the exiting event, saving the array of temporary files used during the session before the application actually closes:

function appExiting(event) { for (i = 0; i < temps.length; i++) { tempFile = temps[i]; tempFile.deleteFile(); } }

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement