Today I’ve discovered an improvement to file uploads from AIR.
Using the upload method from flash.filesystem.File , we’lll send the bytearray uncompressed to a server service. great. However with this little script we can save large amount of bandwidth compressing the bytearray data before sending.
As always feel free to use it and abuse it.
hasta luego!
[as]
package com.mattimatti.remote.io
{
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
/**
* FileUploader class
*
* @author Matteo Monti http://www.mattimatti.com
*
* Utility class to send a bytearray to a server side script.
*
* It differs from method flash.filesystem.File.upload() giving the option to compress bytearray data
* before sending. this results in great advantage in terms bandwidth usage.
*
*
* var fu:FileUploader = new FileUploader();
* fu.addEventListener(Event.COMPLETE,completeHandler);
* fu.upload(“http://www.somehost/service.php”, ba,”somefilename.ext”);
*
*
* Original script from:
* from: http://blog.joa-ebert.com/2006/05/01/save-bytearray-to-file-with-php/
*
*
* PHP SCRIPT
*
*
* $headers = apache_request_headers();
* $fp = fopen( $headers["dest-file-name"], “wb” );
* fwrite( $fp, gzuncompress($GLOBALS[ 'HTTP_RAW_POST_DATA' ]) );
* fclose( $fp );
*
*
*
*/
public class FileUploader extends URLLoader
{
public function FileUploader()
{
super();
}
/**
* saves to server side script a bytearray
*
* @param inUrl the remote service
* @param inByteArray the file ontent
* @param inFileName the destination filename
* @param inCompress do we use compressionover bytearray? yes to make the difference!
*
*/
public function upload(inUrl:String, inByteArray:ByteArray, inFileName:String, inCompress:Boolean = true):void
{
if(!inFileName)throw new Error(“NO FILE NAME SPECIFIED”);
var request:URLRequest = new URLRequest (inUrl);
request.contentType = “application/octet-stream”;
request.method = URLRequestMethod.POST;
// will compress bytearray to be uncompressed later
if(inCompress){
inByteArray.compress();
inByteArray.position = 0;
}
request.data = inByteArray;
var header:URLRequestHeader=new URLRequestHeader(“dest-file-name”,inFileName);
request.requestHeaders.push(header);
load( request );
}
}
}
[/as]
Tags: actionscript 3, AIR, ByteArray
This entry was posted on Monday, March 9th, 2009 at 5:44 am
You can follow any responses to this entry through the RSS 2.0 feed.

Xing
LinkedIn
Twitter
Delicious
Facebook