How to save files from Flex to your server with PHP

For my AMDawing I searched a lot for . And all the solutions that I found are too complex in my opinion. I saw all the examples with remote objects and AMFphp or ZendAMF.

Finally I found the solution at thinkerlog.com. I think it is the most straight forward solution. This are the basics:

First you make the URLrequest that requests the php file url. And then you use URLvariables to send all the variables to the php file. This is the code:

?View Code ACTIONSCRIPT
                        var request:URLRequest = new URLRequest("upload.php");
	         	var vars:URLVariables = new URLVariables();
 
		        vars.name = this.creatorName.text;
		        vars.bindata = Base64.encodeByteArray(imageData);
		        request.method = "POST";
		        var loader:URLLoader = new URLLoader();
		        loader.addEventListener(Event.COMPLETE, uploadPhotoHandler);
		        request.data = vars;
                        loader.load(request);

That is everything at the Flex side. Now the PHP file “upload.php”:

  if ($_REQUEST["bindata"] === NULL) {
    echo "missing parameter.";
  }else {
    $img_data = base64_decode($_REQUEST["bindata"]);
    $name = $_REQUEST["name"] === NULL ? "anonymousn" : $_REQUEST["name"];
    $name = strip_tags($name);
    $img_size = strlen($img_data);
    if ($img_size < 1000000) {
	$date = date("U");
      $img_filename = "data/$name.$date.png";
      unlink($img_filename);
      $img_file = fopen($img_filename, "w") or die("can't open file");
      fwrite($img_file, $img_data);
      fclose($img_file);
	echo "$date";
      echo "$img_size bytes uploaded.";
    }else {
      echo "image too big.";
    }
  }

If you want an extended tutorial you have to go to thinkerlog.com

Author Bio

Leave a reply