The simplest way to send an image from Flash to PHP without user interaction

With the FileReference class, it is quite easy to send an image to the server. But it requires user interaction. What if you need to send an image the user has drawn or captured form the webcam? Then send the data as a ByteArray and let the PHP save the raw data.

The bitmapdata of the image must be encoded to jpg or png and Adobe has classes for that: com.adobe.images.PNGEncoder and com.adobe.images.JPGEncoder. The contentType of the request must be ”application/octet-stream” and if you want to send parameters (file format, username, etc.), add them to the url as parameters: ”simpleSaveImage.php?fileformat=png&filename=cheetach.png”.

In the source files I’m using my ContentLoader to send the data. The sendBytes method  handles everything for you, but here’s also a summary of how to do it without the ContentLoader:


//create the request
var request:URLRequest = new URLRequest("simpleSaveImage.php");
//set the proper contentType
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;

//lets get an image from the library
var img:BitmapData = new Cheetah();

//encode it to PNG
var bytes:ByteArray = PNGEncoder.encode(img);

//put it to the request
request.data = bytes;

//data will be sent with URLLoader
var URLloader = new URLLoader();

//we want to get data (status / filename) back from the server so the dataFormat is set to URLLoaderDataFormat.VARIABLES
URLloader.dataFormat = URLLoaderDataFormat.VARIABLES;

//I wont add listeners here, the complete code is in the example...

The PHP that saves the image and sends back variables:


//get the format
$format = $_REQUEST["format"];

//create uniques file name if filename is not set
$temp = "temp_".time().".".$format;

//get the filename if exists
if(isset($_REQUEST["filename"]) && (strpos($_REQUEST["filename"],".") != -1)) $temp = $_REQUEST["filename"];

//set the folder
$temp ="temp/".$temp;

//get the raw image data
$RAW_POST_DATA = file_get_contents("php://input");

//check that there was data
if(strlen($RAW_POST_DATA) == 0) die("success=false&message=no_data");

//save the file
file_put_contents($temp , $RAW_POST_DATA);

//check if the save was successful
if(filesize($temp) == 0){
 unlink($temp);
 die("success=false&message=filesize0");
}

//report success
die("success=true&message=".urlencode("file saved as ".$temp));

Download source and example files

Kommentoi