Submit your MovieClips to PHP as a multipart form using the UploadPostHelper class. In this example we’ll send a user generated image to TwitPic as a JPEG.

Problem:
Long story short, PHP requires specific headers when submitting an uploaded file. These headers are automatically added when you upload a file from the desktop. What about a user generated file?

Solution:
The UploadPostHelper class automatically adds the required form data to the URLRequest which allows PHP to correctly read the uploaded file as an image. This method can be used to post a user generated image (Sprite, MovieClip… any DisplayObject) to TwitPic.

private var UPLOAD_URL:String = "http://twitpic.com/api/uploadAndPost";
private var _file:FileReference;
private var _loader:URLLoader;
private var _jpgEncoder:JPGEncoder = new JPGEncoder(85);

public function uploadSprite(canvas:Sprite):void
{	
	var jpgSource:BitmapData = new BitmapData(canvas.width, canvas.height);
	jpgSource.draw(canvas);
	var urlVars:URLVariables = new URLVariables();
	urlVars.username = TWITTER_USERNAME;
	urlVars.password = TWITTER_PASSWORD;
	
	var urlRequest:URLRequest = new URLRequest();
	urlRequest.url = UPLOAD_URL;
	urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
	urlRequest.method = URLRequestMethod.POST;
	urlRequest.data = UploadPostHelper.getPostData( 'image.jpg', jpgStream, urlVars );
	urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
	
	// create the image loader & send the image to the server;
	var urlLoader:URLLoader = new URLLoader();
	urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
	urlLoader.addEventListener(Event.COMPLETE, uploadCompleteDataHandler);
	urlLoader.load( urlRequest );
}

Source files can be found here.

Important:
One adjustment does need to be to the UploadPostHelper to be compatible with TwitPic. The upload name for the image must be changed from “Filedata” to “media” for the upload to work correctly.

Resources:
http://labs.findsubstance.com/2008/04/03/as3-upload-encode-images/
http://entrance4.net/labs/?p=51

4 thoughts on “Send Display Objects to PHP as Images

  1. Hey Chris,

    Great post. I have my code working great. It takes a screen shot of my 3D drawing area and posts to TwitPic on my local machine. Once I put it on a server it doesn’t work. What could be the problem? Do I need to post to a PHP script then post to TwitPic?

    Thanks,
    Ryan

  2. TwitPic doesn’t have a crossdomain.xml policy file so you will need to route this through your own server via PHP (or another server side language). I can try and throw together a quick example if you’re interested.

    Cheers,

    Chris

Comments are closed.