Friday, December 21, 2007

Flex multipart/form-data post request

Flex 2 (and 3) are great tools Adobe sent us to try and fix the harm they did with AS2 ;-)
Almost everything we needed was there, except one thing (acctually more...)
There is no way to create a multipart form in order to send any data we want to the server (we're talking ByteArray).
So I wrote a class, It's a lot like UrlRequest, accepting MultipartVariables object as data, here's a short example:


public function startUpload():void {
loader = new MultipartLoader('http://my.uploads.server.com:3007/uploads/test');
var variables:MultipartVariables = new MultipartVariables();
var myByteArray:ByteArray = new ByteArray();
// we will create a fake file content here, you should replace this
// with th ebinary data you want to upload
for(var i:int=0; i<100000;i++) {
myByteArray.writeUTFBytes("123by\nAR\r\nRA\x65\x0156");
}
variables.add('file_data',myByteArray);
variables.add('another_var','extra data');
loader.variables = variables;
loader.addEventListener(Event.COMPLETE,fileUploaded);
loader.load();
}

private function fileUploaded(event:Event):void {
trace(MultipartLoader(event.target).responseBody);
}

The code can be fetched using svn at: https://multipart-loader.googlecode.com/svn/trunk/multipart-loader

or in the google code page:
http://code.google.com/p/multipart-loader/downloads/list

Would love to hear your comments.