Flex Post to php page - actionscript-3

I am trying to post some data from my flex app to a PHP script to be saved.
As a simple test i have made the php script like so
<?php
if ($_POST) {
$message = "Text:" . $_POST['Text'];
mail('vince#myemailaddress.com', 'POSTED!', $message);
} else {
mail('vince#myemailaddress.com', 'No Post Test', 'Testing..');
}
?>
If i hit the script in the browser i receive an email fine. But when i call my flex function i get nothing?
Am i doing it wrong?
private function onTextMessageRecv(event:AsyncDataEvent):void
{
var dialogID:String = event.data;
var strFrom:String = event.data2;
var strTime:String = event.data3;
var MessageStr:String = event.data4;
var variables:URLVariables = new URLVariables()
variables.From = strFrom;
variables.To = m_strUserDisplayName;
variables.Text = MessageStr;
saveIMdata( variables);
}
private function saveIMdata( variables:URLVariables):void
{
LogAddItem( LOG_CATEGORY_MAIN_DEBUG, "Saving IM...");
var myData:URLRequest = new URLRequest("http://im.vlowe.co.uk/save.php")
myData.method = URLRequestMethod.POST
myData.data = variables
var loader:URLLoader = new URLLoader()
loader.dataFormat = URLLoaderDataFormat.VARIABLES
loader.load(myData)
}
I do see the Log entry for "Saving IM...", but no email?
Thanks for any help.
update:
Tried this.. but neither event seems to fire?
private function saveIMdata( variables:URLVariables):void
{
LogAddItem( LOG_CATEGORY_MAIN_DEBUG, "Saving IM...");
var myData:URLRequest = new URLRequest("http://im.vlowe.co.uk/save.php");
myData.method = URLRequestMethod.POST;
myData.data = variables;
LogAddItem( LOG_CATEGORY_MAIN_DEBUG, variables.Text);
var loader:URLLoader = new URLLoader();
LogAddItem( LOG_CATEGORY_MAIN_DEBUG, "Loaded?...");
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(myData);
}
private function onLoadComplete(e:Event):void
{
var loader:URLLoader = URLLoader(e.target);
trace(loader.data);
LogAddItem( LOG_CATEGORY_MAIN_DEBUG, "Load completed");
LogAddItem( LOG_CATEGORY_MAIN_DEBUG, loader.data.toString());
}
private function onLoadError(e:IOErrorEvent):void
{
trace(e.text);
LogAddItem( LOG_CATEGORY_MAIN_DEBUG, "Error " + e.text);
}
Update 2:
my crossdomain.xml
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="80,843,8080,8081,8082" secure="false"/>
</cross-domain-policy>

Sounds to me like a cross domain security issue.
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
[EDIT]
This doesn't exist http://im.vlowe.co.uk/crossdomain.xml
Your crossdomain.xml should look like this. Drop the doctype
<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<allow-access-from domain="*.someDomain.com"/>
</cross-domain-policy>

Add error and complete handlers to your URLLoader and test if the php file is loaded at all :
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
private function onLoadComplete(e:Event):void
{
var loader:URLLoader = URLLoader(e.target);
trace(loader.data);
}
private function onLoadError(e:IOErrorEvent):void
{
trace(e.text);
}
Echo something in your php file and you should see it in your onLoadComplete function.

Related

Cancel a POST request

I have an app that makes a request to a server to generate an audio file and the problem that I have is that if I send two distinct and consecutive requests, I can not cancel the first. I tried with .unload or .unloadAndStop but always gives me error.
Any suggestions?
elfich="sonido" + elfichnum;
var request:URLRequest = new URLRequest();
var variables:URLVariables = new URLVariables();
var loader:URLLoader = new URLLoader();
variables.text=caja_texto;
variables.fileName=elfich;
request.url = "http://192.168.0.19:800/cgi-bin/tts.cgi";
request.method = URLRequestMethod.POST;
request.data = variables;
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, cargacompletanew);
loader.addEventListener(IOErrorEvent.IO_ERROR, onErrornew);
loader.load(request);
}
function cargacompletanew(event:Event):void
{
xlocalSound = new Sound();
var xreq:URLRequest = new URLRequest("http://192.168.0.19:800/output/" + elfich + ".mp3");
xlocalSound.load(xreq);
xlocalSound.addEventListener(Event.OPEN, iniciarSonido);
}
What about
loader.removeEventListener(Event.COMPLETE, cargacompletanew);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onErrornew);
loader.close();
I think there was a problem with close() if you were trying to close it if nothing was loaded, so I'd try to put that inn try/catch block.
try
{
loader.close();
}
catch(e:Error)
{
loader("Oh noes!");
}

Upload a picture to cloudinary using the REST API

We are developing an App using AIR/AS3 and would like to upload a picture to cloudinary via the REST API from the client, instead of using Node.js.
Reading the Documentation of cloudinary, we have found that it should be done via a HTTP/S POST request (http://cloudinary.com/documentation/upload_images#remote_upload).
We've tried using a URLLoader and URLRequest passing the parameters as URLVariables.
Using this as a URL:
'https://api.cloudinary.com/v1_1/'+ CLOUD_NAME +'/raw/upload'
The code looks like this:
public function uploadImage(imageVO:CameraUIImageVO):void {
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, completeHandler, false, 0, true);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler, false, 0, true);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler, false, 0, true);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
var request:URLRequest = new URLRequest(_url);
request.data = getVariables(imageVO);
request.method = URLRequestMethod.POST;
loader.load(request);
}
private function getVariables(imageVO:CameraUIImageVO):URLVariables {
var variables:URLVariables = new URLVariables();
variables.timestamp = _timestamp;
var bitmapData:BitmapData = imageVO.image.bitmapData;
var rawBytes:ByteArray = bitmapData.encode(bitmapData.rect, new JPEGEncoderOptions(50));
variables.file = rawBytes;
variables.resource_type = 'raw';
variables.signature = getSignature("anyPublicId");
variables.api_key = API_KEY;
return variables;
}
private function getSignature(publicId:String):String {
var toHash:String =
"public_id="+ publicId
+ "&timestamp=" + timestamp
+ API_SECRET;
var src:ByteArray = Hex.toArray(Hex.fromString(toHash));
var sha1:SHA1 = new SHA1();
var hashedString:String = Hex.fromArray(sha1.hash( src ));
return hashedString;
}
private function get timestamp():String {
return _timestamp = Number(new Date().time).toString();
}
The result of this is a http error 401
It seems you're signing the public_id, however the public_id isn't passed in options of the upload itself. i.e., there's no:
variables.public_id = "anyPublicId";
inside the getVariables method.

AS3 call function inside loader event function

I have a problem to call a function inside a conditional in another function. I've tried it and it works perfectly but it depends on where the call is made.
Process: I have the checkCode(); function that is called when a form is completed and sent.
private function checkCode():void {
var url = "checktrue.php";
var loader:URLLoader = new URLLoader;
var urlreq:URLRequest = new URLRequest(url);
var urlvars:URLVariables = new URLVariables;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlreq.method = URLRequestMethod.POST;
urlvars.codeVar = formattedCode;
urlreq.data = urlvars;
loader.addEventListener(Event.COMPLETE, completed); //Completed function
status.text = "calling loader";
loader.load(urlreq);
}
When php is complete, "completed" is called and:
private function completed(event:Event = null):void {
var loader2: URLLoader = URLLoader(event.target);
var checked:String = loader2.data.checked;
var codetrue:String = loader2.data.codetrue;
if(checked == "1" || codetrue == null || codetrue == "") {
trace("WRONG");
}
else{
download(); //download function
trace("ok");
}
}
Here I get the php vars and check if they are valid to call the download() function.
public function download():void {
req = new URLRequest(proxy + filename);
file = new FileReference();
file.addEventListener(Event.COMPLETE, completeHandler);
file.addEventListener(Event.CANCEL, cancelHandler);
file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
file.download(req, "file.zip");
}
It is possible this function cannt be called from the "completed" loader function?
Thank you very much!
You need to put the download function in another button for the correct use. Or create your own event.

passing parameters to CGI script using flex

I am trying to pass three parameters (arg1, arg2 and arg3) to a CGI script but the following code is not working.
Can someone show me how to pass parameters to a CGI script using flex?
public function loadURL():void {
//frameBuffer.reloadFrame(frameBuffer.currentFrame);
var variables:URLVariables = new URLVariables("name=Franklin");
var request:URLRequest = new URLRequest();
request.url = "http://firefly.cs.missouri.edu/cgi-bin/main2.cgi?arg1=image.TIF&arg2=BranchPoints.txt&arg3=Medial.txt";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, completeHandler);
try
{
loader.load(request);
}
catch (error:Error)
{
trace("Unable to load URL");
}
function completeHandler(event:Event):void
{
trace(event.target.data.welcomeMessage);
}
//Alert.show("Hi");
}
Do it like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" minWidth="955" minHeight="600" creationComplete="init(event)">
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
public function loadURL():void
{
var variables:URLVariables = new URLVariables();
variables.name = "Franklin";
variables.arg1 = "image.TIF";
variables.arg2 = "BranchPoints.txt";
variables.arg3 = "Medial.txt";
var request:URLRequest = new URLRequest("http://firefly.cs.missouri.edu/cgi-bin/main2.cgi");
request.method = "POST";
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.load(request);
}
private function completeHandler(event:Event):void
{
trace(event.target.data.welcomeMessage);
}
private function onError(event:IOErrorEvent):void
{
trace("Fault!");
}
protected function init(event:FlexEvent):void
{
loadURL();
}
]]>
</mx:Script>
</mx:Application>
The script gave me back the following code:
<html><head><title>My First Script</title></head>
<body>
<p>Hello world!</p>
</body></html>image.TIFBranchPoints.txtMedial.txtimage.TIF BranchPoints.txt Medial.txt

AS3/AIR: IOStream Error when trying to upload files

I'm making an AIR app in which the user drags and drops image files onto the stage, the app then uploads those dropped images to the site imgur.com, and then returns with links to the images (in XML format).
I am having two issues:
the program works successfully with a very small file, however anything larger (1mb or more), I get an IOStream error 2023. Imgur supports uploads of up to 10mb so I know it must be something on my end.
I would like to be able to drop multiple image files at once into the program, and have it upload all of them (either synchronously or asynchronously, it does not matter). Right now the program gives errors when I attempt to do this (something along the lines of the byteArray having to be greater than 0).
Below is the code in question which is giving me issues. (thank you for your help in advanced)
private function doDragDrop(e:NativeDragEvent):void
{
trace("doDragDrop() called.");
var dropFiles:Array = e.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
for each (var file:File in dropFiles)
{
switch (file.extension.toLowerCase())
{
case "jpg" :
case "jpeg" :
case "gif" :
case "png" :
case "apng" :
case "tiff" :
case "bmp" :
case "pdf" :
case "xcf" :
trace("file Extension Check = passed");
addImage(file.nativePath);
break;
//error handling for non-supported filetypes
default :
trace("ERROR: Unsupported File Type Detected!");
}
}
}
private function addImage(nativePath:String):void
{
trace("addImage() called.");
trace("NativePath is: " + nativePath);
//var file:File = new File(nativePath);
var file:File = File.desktopDirectory.resolvePath(nativePath);
var ba:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
stream.readBytes(ba);
stream.close();
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, fileLoaded);
loader.loadBytes(ba);
}
private function fileLoaded(e:Event):void
{
trace("fileLoaded() called.");
var bitmap:Bitmap = Bitmap(e.target.content);
var bitmapData:BitmapData = bitmap.bitmapData;
var png:ByteArray = PNGEncoder.encode(bitmapData);
urlLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, onCookieSent);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
request.data = png;
urlLoader.load(request);
}
private function onCookieSent(e:Event):void
{
trace("onCookieSent() called.");
var res:XML = new XML(unescape(urlLoader.data));
var resultsList:XMLList = res.links;
trace(resultsList);
}
private function onIOError(e:IOErrorEvent):void
{
trace("ioErrorHandler: " + e);
TweenLite.to(tv_mc, 2, {alpha:0.5, scaleX:1.0, scaleY:1.0, ease:Elastic.easeOut});
// Handle error
}
private function onSecurityError(e:SecurityErrorEvent):void
{
trace("securityErrorHandler: " + e);
TweenLite.to(tv_mc, 2, {alpha:0.5, scaleX:1.0, scaleY:1.0, ease:Elastic.easeOut});
// handle error
}
//When the dragged object leaves the drop point, do this
private function doDragExit(e:NativeDragEvent):void
{
trace("doDragExit() called.");
TweenLite.to(tv_mc, 2, {alpha:0.5, scaleX:1.0, scaleY:1.0, ease:Elastic.easeOut});
}
after doing this:
var ba:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
stream.readBytes(ba);
stream.close();
you already have a ByteArray of the file/image. can't you just send this one...
private function addImage(nativePath:String):void
{
trace("addImage() called.");
trace("NativePath is: " + nativePath);
//var file:File = new File(nativePath);
var file:File = File.desktopDirectory.resolvePath(nativePath);
var ba:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
stream.readBytes(ba);
stream.close();
urlLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, onCookieSent);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
request.data = ba;
urlLoader.load(request);
}