How to Send a Bytearray (From Flash) and Some Form Data to PHP

How can I send a ByteArray (from Flash) and some form data to php?

it's a little tricky: You can do it one of two ways:

Arthem posted this in another thread:

This was of great help to me:
http://www.quietless.com/kitchen/upload-bitmapdata-snapshot-to-server-in-as3/

You need to modify the
URLRequestWrapper to insert field
names and file names where needed.
Here's what I've done:

bytes = 'Content-Disposition:
form-data; name="' + $fieldName + '";
filename="';

It does the most formatting of headers
so the server could understand it as a
file upload.

By the way, if you have a BitmapData
you might need to encode it to JPEG or
PNG first.

And I usually use this solution:

I haven't used the imageshack API, but you may want to try using adobe's JPGEncoder class - here's a quick example that passes a username and the JPG's byte array, it's really quite simple.

private function savePicToServer(bmpData:BitmapData):void
{
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(bmpData);

var loader:URLLoader = new URLLoader();
configureListeners(loader);

var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var request:URLRequest = new URLRequest(ModelLocator.BASE_URL + ModelLocator.UPLOAD_URL + "?user=" + ModelLocator.getInstance().username);
request.requestHeaders.push(header);
request.method = URLRequestMethod.POST;
request.data = jpgStream;
loader.load(request);
}

Note that the variables are passed as part of the query string. You can't use URLVariables, as several people have suggested, as the URLVariables would be stored in the request's data property, which we are already using to pass the byteArray.

How to send a FLV format data in byteArray using URLloader to a php script?

Just figured this out.

I can now successfully send the flv byteArray in a php script where then the php receives it and save it as flv file in local system and uploading it in the youtube server using zend framework.

here's my code in flash.

            //send byteArray to a php script
var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
var request:URLRequest = new URLRequest(url);

request.requestHeaders.push (header);
request.method = URLRequestMethod.POST;

request.data = fs; //FLV byteArray
var loader:URLLoader = new URLLoader();
trace(request.data);
loader.load(request)

and the scipt that receives and save it as a flv file:

        $im =  $GLOBALS["HTTP_RAW_POST_DATA"];
$fp = fopen("testVid.flv", 'w');
fwrite($fp, $im);
fclose($fp);

It turns out that I really dont need to encode the byteArray like what the JPEGEncoder is doing. Im still very new in flash and php though. And I have no idea if this is the best practice I can have. An advice would be greatly appreciated. Thanks guys.

How to send byte array with image from AS3 to PHP?

import com.sociodox.utils.Base64;
.....
//BA1 is ByteArray with an image encoded
var enc_image=Base64.encode(BA1);
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
var request:URLRequest = new URLRequest("some.php");
var variables:URLVariables = new URLVariables();
variables.decode("image="+enc_image);
request.method = URLRequestMethod.POST;
request.data = variables;
loader.load(request);

of course, set your listeners, too...

in "some.php":

$imageData = base64_decode(str_replace(" ", "+", $_POST['image']));
$fh = fopen("path/to/image/somename.jpg", "wb");
fwrite($fh, $imageData);
fclose($fh);

This works like a charm :)

Send an Actionscript ByteArray as a POST variable (within Facebook)

I think the easiest way is base64 encoding the image before sending it. Then it's just a string and it's safe to pass it as a regular POST variable.

On the php side, you just have to base64_decode this string and then you have your image data ready to save it to file or whatever you need (you could also feed it to GD or other such library if you need to manipulate it first).

Another option, at least in theory is using multipart/data, just like you'd use in an html form to send a file, but if I recall correctly, the player does not allow to send files using this method (until version 9.0.124 or something like that, this was possible).

So, base64 is easy and simple and it only adds some overhead; 1/3 of the file payload in terms of size and some processing time as weel, but in most cases this isn't a big deal.

Sending data from Flash to PHP using POST method

Not sure about how to convert your image into data and such, but here's a class I have lying around that you can use to transfer data to a PHP script (which can from there insert the data into a database).

package
{
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.events.Event;

/**
* @author Marty Wallace
* @version 1.00
*/
public class PHPData extends Object
{
/**
* Sends data to a PHP script
* @param script A URL to the PHP script
*/
public function send(script:String, vars:URLVariables):void
{
var req:URLRequest = new URLRequest(script);

req.data = vars;
req.method = URLRequestMethod.POST;

var loader:URLLoader = new URLLoader();
loader.load(req);

// listeners
loader.addEventListener(Event.COMPLETE, _complete);
}

/**
* Called when a response has been received from a PHP script
* @param e Event.COMPLETE
*/
private function _complete(e:Event):void
{
var vars:URLVariables = new URLVariables(e.target.data);

var i:String;
for(i in vars)
{
trace(i + ": " + vars[i]);
}

e.target.removeEventListener(Event.COMPLETE, _complete);
}
}
}

Use:

var php:PHPData = new PHPData();
var vars:URLVariables = new URLVariables();

vars.imagedata = your_image_data;

php.send("your_php_script.php", vars);

Sending multipart/form-data with image files from Actionscript to PHP

This class is working for me for this case: https://github.com/jonasmonnier/Multipart.as

Saving entire Flash document as JPEG to email as an attachment

I think it is possible.
First you convert the displayObject in wich the design is into a byteArray wich you send to php. where you create an image using the imagecreatefromstring() function see: http://lv.php.net/imagecreatefromstring.

Example AS3

public function displayObjectToPNG(displayObject:*, scale:Number = 1):ByteArray {
var bmpData:BitmapData=new BitmapData(displayObject.width, displayObject.height, true, 0xFFFFFF);
bmpData.draw(displayObject);

var byteArray:ByteArray = PNGEncoder.encode(bmpData);
return byteArray;
}
public function encodeFile(byteArray:ByteArray):Base64Encoder {
var base64:Base64Encoder = new Base64Encoder();
base64.encodeBytes(byteArray);
return base64;
}
public function saveFile(encodedFile:Base64Encoder, scriptLocation:String):void {
var data:URLVariables = new URLVariables();
data.fileData = encodedFile;

var request:URLRequest = new URLRequest(scriptLocation);
request.method = URLRequestMethod.POST;
request.data = data;

var loader:URLLoader= new URLLoader();
loader.addEventListener(Event.COMPLETE, function(e:Event):void {fileSaved(loader);});
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioError);
_fileSavesInProgress.push(loader);

try {
loader.load(request);
} catch (e:*) {
trace("an error occured of type", e);
}
}

Implement like this (this is the code you would execute when the user clicks the button):

saveFile(encodeFile(displayObjectToPNG(sprite)), "http://www.your.domain/php/sendMail.php");

Your php file will look something like this.

<?php
$png = imagecreatefromstring(base64_decode($fileData));

function mail_attachment($to, $subject, $message, $from, $file) {
$content = chunk_split($file);
$uid = md5(uniqid(time()));
$from = str_replace(array("\r", "\n"), '', $from); // to prevent email injection
$header = "From: ".$from."\r\n"
."MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"
."This is a multi-part message in MIME format.\r\n"
."--".$uid."\r\n"
."Content-type:text/plain; charset=iso-8859-1\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
.$message."\r\n\r\n"
."--".$uid."\r\n"
."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
.$content."\r\n\r\n"
."--".$uid."--";
return mail($to, $subject, "", $header);
}

mail_attachment("client", "subject", "your design", "your@company.com", $png);

Note that I have not tested this but I think this will be very close if not the solution.
Good luck!

[Edit] If you want to implement this solution in one function use the following AS3 code:

public function sendSprite(sprite:Sprite, scriptLocation:String):void {
var bmpData:BitmapData=new BitmapData(sprite.width, sprite.height, true, 0xFFFFFF);
bmpData.draw(sprite);

var encodedFile:Base64Encoder = new Base64Encoder();
encodedFile.encodeBytes(PNGEncoder.encode(bmpData));

var data:URLVariables = new URLVariables();
data.fileData = encodedFile;

var request:URLRequest = new URLRequest(scriptLocation);
request.method = URLRequestMethod.POST;
request.data = data;

var loader:URLLoader= new URLLoader();
loader.addEventListener(Event.COMPLETE, spriteSend);
loader.addEventListener(Event.OPEN, traceEvent);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, traceEvent);
loader.addEventListener(IOErrorEvent.IO_ERROR, traceEvent);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, traceEvent);
loader.addEventListener(ProgressEvent.PROGRESS, traceEvent);

try {
loader.load(request);
} catch (e:*) {
trace("an error occured of type", e);
}

function traceEvent(e:*):void {
trace(e);
}

function spriteSend(e:Event):void {
trace(e, "\n sprite succesfully send \n");
}

}

Passing an ActionScript JPG Byte Array to Javascript (and eventually to PHP)

I'm not sure why you would want to use Javascript here. Anyway, the string you pasted looks like the beginning of a JPG header. The problem is that a JPG will for sure contain NULs (characters with 0 as its value). This will most likely truncate the string (as it seems to be the case with the sample you posted). If you want to "stringify" the JPG, the standard approach is encoding it as Base 64.

If you want to persist data locally, however, there's a way to do it in Flash. It's simple, but it has some limitations.

You can use a local Shared Object for this. By default, there's a 100 Kb limit, which is rather inadequate for image files; you could ask the user to allot more space to your app, though. In any case, I'd try to store the image as JPG, not the raw pixels, since the difference in size is very significative.

Shared Objects will handle serialization / deserialization for you transparently. There are some caveats: not every object can really be serialized; for starters, it has to have a parameterless constructor; DisplayObjects such as Sprites, MovieClips, etc, won't work. It's possible to serialize a ByteArray, however, so you could save your JPGs locally (if the user allows for the extra space). You should use AMF3 as the encoding scheme (which is the default, I think); also, you should map the class you're serializing with registerClassAlias to preserve the type of serialized the object (otherwise it will be treated as an Object object). You only need to do it once in the app life cycle, but it must be done before any read / write to the Shared Object.

Something along the lines of:

registerClassAlias("flash.utils.ByteArray",ByteArray);

I'd use Shared Objects rather than Javascript. Just keep in mind that you'll most likely have to ask the user to give you more space for storing the images (which seems reasonable enough if you're allowing them to work offline), and that the user could delete the data at any time (just like he could delete their browser's cookies).

Edit

I realize I didn't really pay much attention the "we have chosen Gears to do so" part of your question.

In that case, you could give the base 64 approach a try to pass the data to JS. From the Actionscript side it's easy (grab one of the many available Base64 encoders/decoders out there), and I assume the Gear's API must have an encoder / decoder available already (or at least it shouldn't be hard to find one). At that point you'll probably have to turn that into a Blob and store it to disk (maybe using the BlobAPI, but I'm not sure as I don't have experience with Gears).



Related Topics



Leave a reply



Submit