I would like to be able to display an image on the file script.php with the help of data transmitted by this code (Actionscript)
I get data by the POST method but I do not know what to do with it.
header('Content-Type: image/jpeg');
I don't know what to do with $_POST
public function onTakePhoto(param1:Event) : void
{
var _loc1_:Bitmap = new Bitmap(new BitmapData(680,440));
var _loc2_:Matrix = new Matrix();
_loc2_.translate(-290,-150);
_loc2_.scale(2,2);
_loc1_.bitmapData.draw(DisplayObject(something),_loc2_);
var _loc3_:ByteArray = new ByteArray();
_loc1_.bitmapData.encode(_loc1_.bitmapData.rect,new JPEGEncoderOptions(),_loc3_);
var _loc4_:URLRequest = new URLRequest("script.php");
_loc4_.method = URLRequestMethod.POST;
_loc4_.data = _loc3_;
navigateToURL(_loc4_,"_blank");
_loc1_.bitmapData.dispose();
}
You can fetch the $_POST data like this:
$image_data = file_get_contents("php://input");
//proceed by perhaps saving the image to the server:
file_put_contents('path/to/save/image.jpg',$image_data);
Related
I'm trying to send data to a PHP file via JSON but i'm getting an error when trying to JSON the data.
I'm pretty sure i'm doing this right. Any suggestions ?
Here's my ActionScript 3 code :
var dataToSend:Array = new Array();
var data:Object = new Object();
data.callFunction = "getQuestion";
data.numberOfQuestions = "1";
dataToSend.push(data);
trace(data);
var variables:URLVariables = new URLVariables();
variables.data = JSON.stringify(dataToSend);
var url:String = "myurl";
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.load(request);
loader.addEventListener(Event.COMPLETE, requestComplete);
And my PHP code :
if $data[ "callfunction" ] = "getQuestion";
{
echo("Sent");
}
Your ActionScript 3 code looks fine but you have some problems in your PHP's one.
Let's see that.
The if statement in PHP is like the AS3's one :
<?php
if( condition )
instruction;
?>
The equality operator is the == and not the assignment one ( = ).
As you have sent your data using the POST method, you can use the PHP's $_POST array to get it.
Then, as you have sent it on JSON format, you can decode it using the decode_json() function in your PHP side.
So your PHP code can be like this for example :
<?php
if(isset($_POST['data']))
{
$data = $_POST['data'];
$json_data = json_decode($data);
if($json_data[0]->callFunction == "getQuestion")
{
echo("Sent");
}
}
?>
Then you can get the response of your PHP script in your AS3 requestComplete function :
function requestComplete(e:Event): void
{
trace(URLLoader(e.target).data); // gives : Sent, for example
}
...
Hope that can help.
Okay, here goes. I'm sure I'm only missing a small thing somewhere.
I'm trying to do a little Highscore System for my game and thus I have a php script on a webspace for the programm to access (I have literally 0 experience with php):
<?php
$json = json_encode($_REQUEST);
$fileSave = fopen("processdata.txt", "a+") or die ("Can't create processdata.txt");
fwrite($fileSave, $json);
fclose($fileSave);
print($json);
?>
processdata.php
then, in actionscript, I juse this code to access the file and parse it:
//set variables to send to the php script
var variables:URLVariables = new URLVariables();
variables["name"] = "Player1";
variables["points"] = 123;
//set request to load php script
var request:URLRequest = new URLRequest("processdata.php");
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, httpRequestComplete);
loader.load(request);
//php script finished
function httpRequestComplete(_e:Event){
//load processdata.txt
var uLoader:URLLoader = new URLLoader();
var uReq:URLRequest = new URLRequest("processdata.txt");
uLoader.addEventListener(Event.COMPLETE, getProcessdata);
uLoader.load(uReq);
}
//loading of processdata.txt finished
function getProcessdata(_e:Event){
var rawData : String = _e.target.data;
//convert the input string in readable JSON
rawData = rawData.split('"').join("\\\"");
rawData = "\"" + rawData + "\"";
//convert into JSON
var proData:Object = JSON.parse(rawData);
}
here is what processdata.txt looks like (for example)
{"name":"Player1","points":"123"}{"name":"Player2","points":"234"}
this is then converted in my AC into this (to make it readable for the JSON.parse):
"{\"name\":\"Player1\",\"points\":\"123\"}{\"name\":\"Player2\",\"points\":\"234\"}"
Now, how to I access the parsed JSON String? I tried all of those and nothing works:
proData.name;
proData[name];
proData["name"];
proData[0];
proData[name[0]];
for (var obj : String in proData){
obj;
}
Any help is appreciated. Doesn't matter where you find a possibility to make this work (PHP, AC3, JSON, etc)
Also, if you have a simple possibility for me to change my php in a way that it creates xml instead of php, I can do the rest from there, I get my Code to work with a XML File.
Thanks in advance.
You should know that your JSON content is not valid and that's why you can get nothing from it in the ActionScript side.
As you are saving players scores, you can store your data as an array :
[
{
"name": "Player1",
"points": "123"
}, {
"name": "Player2",
"points": "234"
}
]
but to get that, you've to edit your PHP code like this, for example :
<?php
$json_file = 'scores.json';
$new_score = $_REQUEST;
if(file_exists($json_file))
{
// get stored scores
$scores = json_decode(file_get_contents($json_file));
} else {
// create an empty array to store scores
$scores = array();
}
// add the new score to scores array
array_push($scores, $new_score);
// persist scores array as json content
file_put_contents($json_file, json_encode($scores));
?>
then in the ActionScript side, you can do :
function getProcessdata(e:Event) : void
{
var rawData:String = e.target.data;
var data:Array = JSON.parse(rawData) as Array;
for(var i:int = 0; i < data.length; i++){
trace(data[i].name); // gives for example : "Player1"
}
}
Hope that can help.
I have a video player built in AS3. I take a snapshot of the video player using this code:
var uploadUrl = 'http://localhost:8000/assets/uploadframegrab';
var bitmap = new Bitmap();
var graphicsData : Vector.<IGraphicsData>;
graphicsData = container.graphics.readGraphicsData();
bitmap.bitmapData = GraphicsBitmapFill(graphicsData[0]).bitmapData;
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(bitmap.bitmapData);
var loader:URLLoader = new URLLoader();
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var csrf:URLRequestHeader = new URLRequestHeader("X-CSRF-Token", csrfToken);
var request:URLRequest = new URLRequest(uploadUrl);
request.requestHeaders.push(header);
request.requestHeaders.push(csrf);
request.method = URLRequestMethod.POST;
request.data = jpgStream;
loader.load(request);
I need to upload the encoded to JPG using one of my Laravel routes. My route looks like:
Route::post('assets/uploadframegrab', 'AssetController#uploadFramegrab');
When I run the AS3 code, it calls the laravel route, but my $request variable appears to be empty. The Request Payload property on the network info tab that shows all my headers and stuff contains what looks like the source of the image file.
If I do a return Response::json(['filedata' => $request]); all I get is this:
filedata: {
attributes: {},
request: {},
query: {},
server: {},
files: {},
cookies: {},
headers: {}
}
My uploadFramegrab function is simply this for now:
public function uploadFramegrab(Request $request)
{
if ($request)
{
return Response::json(['filedata' => $request]);
}
else
{
return Response::json(['error' => 'no file uploaded']);
}
}
I've searched online but I cannot find anything specifically for uploading from flash to laravel. I've done it javascript to laravel no problem. Anyone know what this could be? If you'd like more information please ask.
To do that, you can use the Multipart.as ( AS3 multipart form data request generator ) from Jonas Monnier. It's really very easy to use it, take a look on this example ( using the basic example from the github project's page ) :
var upload_url:String = 'http://www.example.com/upload';
// create an orange square
var bmp_data:BitmapData = new BitmapData(400, 400, false, 0xff9900);
// compress our BitmapData as a jpg image
var image:ByteArray = new JPGEncoder(75).encode(bmp_data);
// create our Multipart form
var form:Multipart = new Multipart(upload_url);
// add some fields if you need to send some informations
form.addField('name', 'bmp.jpg');
form.addField('size', image.length.toString());
// add our image
form.addFile('image', image, 'image/jpeg', 'bmp.jpg');
var loader:URLLoader = new URLLoader();
loader.load(form.request);
Then, in the PHP side, you do as you have usually did :
public function upload(\Illuminate\Http\Request $request)
{
if($request->hasFile('image'))
{
$file = $request->file('image');
$upload_success = $file->move($your_upload_dir, $file->getClientOriginalName());
if($upload_success)
{
return('The file "'.$request->get('name').'" was successfully uploaded');
}
else
{
return('An error has occurred !');
}
}
return('There is no "image" file !');
}
Hope that can help.
Based on the doc for AS3 (emphasis mine):
The way in which the data is used depends on the type of object used:
If the object is a ByteArray object, the binary data of the ByteArray object is used as POST data. For GET, data of ByteArray type is not supported. Also, data of ByteArray type is not supported for FileReference.upload() and FileReference.download().
If the object is a URLVariables object and the method is POST, the variables are encoded using x-www-form-urlencoded format and the resulting string is used as POST data. An exception is a call to FileReference.upload(), in which the variables are sent as separate fields in a multipart/form-data post.
You're clearly in the first case here.
From the Laravel Requests doc:
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller constructor or method. The current request instance will automatically be injected by the service container.
The Request class API:
string|resource getContent(bool $asResource = false)
Returns the request body content.
Putting it together:
public function uploadFramegrab(Request $request) {
$content = $request->getContent();
$fileSize = strlen($content);
}
In Laravel 4:
$csrf = Request::header('X-CSRF-Token');
// Add a header like this if you want to control filename from AS3
$fileName = Request::header('X-File-Name');
$content = Request::getContent(); // This the raw JPG byte array
$fileSize = strlen($content);
Last time I checked Laravel uses php://input to read the request body. See this answer for more info.
I'm trying to pass some variables from php to flash, im using this actionscript code:
public function gameOver(score:Number)
{
totalScore.text = score.toString();
var scriptVars:URLVariables = new URLVariables();
scriptVars.score = score;
var scriptLoader:URLLoader = new URLLoader();
var scriptRequest:URLRequest = new URLRequest("checkScores.php");
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
}
function handleLoadSuccessful(e:Event):void
{
trace("Scores Loaded");
var vars:URLVariables = new URLVariables(e.target.data);
nickname1.text = vars.nickname;
score1.text = vars.score;
}
function handleLoadError($evt:IOErrorEvent):void
{
trace("Load failed.");
nickname1.text ="error";
}
And this php code:
<?php
... some code for the mysql connection and select sentence ...
$topScores = mysqli_query($con, $topScores);
$topScores = mysqli_fetch_array($topScores);
echo "&nickname=$topScores[nickname]&score=$topScores[score]";
?>
both runs without errors, the problem is that what i get on flash aren't the variables values but the name of the variables, in other words what i get on vars.nickname is
$topScores[nickname]
and for vars.score
$topScores[score]
If i run the php alone i get this:
&nickname=jonny&score=100
which are the actual variable values i'm trying to get, any help would be greatly appreciated.
I think you may just be loading up the php file as a text file from flash. Can you change the following line:
new URLRequest("checkScores.php");
to something like:
new URLRequest("http://localhost/checkScores.php");
or whatever you see in the browser address bar when you "run" it as you said in your question.
I need to make a SWF that should show some data from the DB.
The DB will be read using PHP.
I was thinking that the SWF would get the data by accessing "data.php" and data.php will read from the DB. The SWF would read the XML/JSON/RAW DATA from that file and update it's variables.
How can I do this ? any reference maybe ?
Thanks!
The best way to intercommunicate Flash and PHP is XML (don't forget to use UTF-8!).
in "data.php":
$xml = new DOMDocument('1.0', 'UTF-8');
$doc = $xml->appendChild($xml->createElement('my-root-element'));
...
header('Content-Type: text/xml; charset=utf-8');
echo $xml->saveXML();
In "test.as"
var myLoader:URLLoader = new URLLoader();
var req:URLRequest = new URLRequest('http://.../data.php');
myLoader.addEventListener(Event.COMPLETE, onMyXMLLoad);
myLoader.load(req);
function onMyXMLLoad(e:Event)
{
trace(e.target.data);
var xml:XML = new XML(e.target.data);
...
}