Posts Tagged GET

Sending byteArray (image) and variables to server-side script as POST data in AS3

A couple things here, I first talked about how to send an image and variables to the server (at the same time) on this post, but it felt a bit weird, the file had no name to retrieve it and the variables were sent as GET. Now while working a with a new colleague, he showed me this code that for him was nothing but for me was amazing. It is a little library called UploadPostHelper made by Jonathan Marston back in 2007 (2007! why didn’t someone talk to me about this library before!!!).

Anyway here is a little code snippet showing how to use it:

var jpegEncoder:JPGEncoder = new JPGEncoder(85); //using the JPGEncoder from as3corelib
var jpegBytes:ByteArray = jpegEncoder.encode(myPicture.bitmapData); //encoding a Bitmap into a ByteArray
 
var urlRequest : URLRequest = new URLRequest();
urlRequest.url = "THE URL OF YOUR SERVER SIDE SCRIPT";
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
 
//now create an object with the variables you want to send as POST
var postVariables:Object{variable1Name:variable1Data, variable21Name:variable2Data, variable3Name:variable3Data}
urlRequest.data = UploadPostHelper.getPostData( 'image.jpg', jpegBytes,"filedata", postVariables); //here is where the magic happens, filedata will be the name to retrieve the file
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
 
//from here it is just a normal URLLoader
_pictureUploader = new URLLoader();
_pictureUploader.dataFormat = URLLoaderDataFormat.BINARY;
_pictureUploader.addEventListener( Event.COMPLETE, _onUploadComplete, false, 0, true );
_pictureUploader.load( urlRequest );

How easy and beautiful is that?

So can get the code for the UploadPostHelper at the bottom of this post or I have made a zip file with the .as file here.

Dude, 2007!

, , , , , , , ,

10 Comments