File uploads with Adobe Flex and Zend AMF

October 20, 2010

Uncategorized

Zend AMF is a PHP implementation of the AMF (Action Message Format) binary protocol within the ZendFramework. I had to implement a system to upload files that were a little different than what is typically used in Flash, so I built upon Zend AMF for my needs.

Researching a little on the net, I found a solution that was simpler than I expected. Based on an article, I only had to make a few adjustments.

Begin with our gateway to be used as endpoint in Adobe Flex.

require_once 'Zend/Amf/Server.php';
require_once 'Zend/Amf/Exception.php';
require_once 'br/com/leonardofranca/vo/FileVO.php';
require_once 'br/com/leonardofranca/UploadZendAMF.php';

$server = new Zend_Amf_Server();
$server->setProduction(false);

$server->setClass('UploadZendAMF');

$server->setClassMap('FileVO',"br.com.leonardofranca.vo.FileVO");

echo($server->handle());

First VO properties with the file name and binaries.

class FileVO
{
    public $_explicitType = 'br.com.leonardofranca.vo.FileVO';
    public $fileName;
    public $fileData;
    
    function __construct ()
    {}
    
	public function getFileName() 
	{
		return $this->fileName;
	}

	public function setFileName($fileName) 
	{
		$this->fileName = $fileName;
	}

	public function getFileData() 
	{
		return $this->fileData;
	}

	public function setFileData($fileData) 
	{
		$this->fileData = $fileData;
	}
}

Now our PHP class to process the uploading:

class UploadZendAMF  
{
    public function __construct()
    {
      
    }
    
    public function upload(FileVO $data)
    {
        try 
	    {
		$fileData = $data->getFileData();
		file_put_contents( 'C:\\apache\\htdocs\\images\\' . $data->getFileName(), $fileData);
	        return true;	
	    } 
	    catch (Exception $e) 
	    {
	        throw new Exception($e->getMessage());
	    }
    }
}

Now we add the view layer using Adobe Flex, starting with our VO:

package br.com.leonardofranca.vo
{
	import flash.utils.ByteArray;

	[Bindable]
	[RemoteClass(alias="br.com.leonardofranca.vo.FileVO")]
	public class FileVO
	{
		private var _fileName:String;
		private var _fileData:ByteArray;
		
		public function FileVO()
		{
		}

		public function get fileName():String
		{
			return _fileName;
		}

		public function set fileName(value:String):void
		{
			_fileName = value;
		}

		public function get fileData():ByteArray
		{
			return _fileData;
		}

		public function set fileData(value:ByteArray):void
		{
			_fileData = value;
		}

	}
}

Now our mxml that will load the bytes from the file to send to Zend AMF for encoding and transfer. Explore the full source code on my site.

My blog: http://www.leonardofranca.com

Comments are closed.