Upload to server with Adobe AIR and JavaScript

It is simple example of how to upload local file to server with JavaScript and Adobe AIR

Example.

// sample url and file path which we use for upload
var url = "http://img31.picoodle.com/upload.php";
var pictureFile = new air.File('/path/to/local.file');

// creating POST request variables (like in html form fields)
var variables = new air.URLVariables();
variables.op = 'upload';

// set params for http request
var tmpRequest = new air.URLRequest(url);
tmpRequest.method = air.URLRequestMethod.POST;
tmpRequest.contentType = 'multipart/form-data'; // это тип для загрузки файлов
// assigning variables to request
tmpRequest.data = variables;
air.sendToURL(tmpRequest);

// attach events for displaying progress bar and upload complete
pictureFile.addEventListener(air.ProgressEvent.PROGRESS, callback_for_upload_progress);
pictureFile.addEventListener(air.DataEvent.UPLOAD_COMPLETE_DATA, callback_for_upload_finish); 

// doing upload request to server
pictureFile.upload(tmpRequest, 'pic', false);

Interesting thing that I was unable to find event for tracking upload complete in JavaScript docs of AIR. I’ve got it via Flex/AcionScript docs. It is air.DataEvent.UPLOAD_COMPLETE_DATA.

To complete this example I created two sample event handlers for upload progress and complete.

function callback_for_upload_progress(event) { 
    var loaded = event.bytesLoaded; 
    var total = event.bytesTotal; 
    var pct = Math.ceil( ( loaded / total ) * 100 ); 
    air.trace('Uploaded ' + pct.toString() + '%');
}

function callback_for_upload_finish(event) {
    Console.log('File upload complete');
    air.trace(event.data); // output of server response to AIR dev console
}

This example is for devs that have some experience with AIR. Later I’ll write some complete example from scratch. Stay tuned with the AIR tag ;-)


Tags

Blogroll

Recent bookmarks