Upload file to server in as3 - actionscript-3

How to upload a File to server in as3? I don't want to browse file by using FileReference.browse(). I tried using URLLoader to get the file and convert to byteArray but as I send it to server using URLVariables it gives IOError=2032. I want update database on the server. The structure would be like
email (string)
sqlite_db (Blob)
I have to send both of these variables inside one request. Any idea!

The upload process is made much easier by using the UploadPostHelper which is a great class to create multipart data forms:
ByteArray byteArray = [YOUR FILE DATA];
var urlRequest : URLRequest = new URLRequest();
urlRequest.url = 'http://your.server.com/destination';
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data =
UploadPostHelper.getPostData(
'filename.ext',
byteArray,
{
email:"emailParameter",
other:"otherParameter"
} );
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
// create a loader & send the file to the server;
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load( urlRequest );
And of course you can listen to the complete event and pass back any information from your server. Hope that helps.

Related

getting POST using URLRequest + if statement syntax issue

I'm trying to get the reply from the address specified in var url:String, which is either 0 or 1. If the reply is 1 then it must set currentState = CallFailed (as seen below). The client compiles without error (using Adobe Flash Builder 4.6) and seems to successfully reach var url:String, but doesn't seem to be getting the response\and or my if statement is incorrect.
Actionscript:
// check to see if block.php replies 0 or 1
var url:String = "https://domain.com/block.php?postid=" + calleeInput.text + "";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
request.data = variables;
request.method = URLRequestMethod.POST;
navigateToURL(request);
if (request.data == 1)
{
// if reply is 1 then cancel the call
currentState = CallFailed;
return;
}
PHP:
PHP will echo 0 or 1 when block.php is loaded. It's not encoded in any format such as JSON\AJAX.
It seems you want data from the server. Perhaps the URLLoader class would be better?
var url:String = "https://domain.com/block.php?postid=" + calleeInput.text + "";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
request.data = variables;
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener( Event.COMPLETE,
function( e:Event ) : void
{
// your response data will be here
// you'll have to verify the format
trace( e.target.data );
}
)
loader.load( request );
Put a breakpoint at the trace statement and check out the contents of e.target.data, and go from there
The purpose of navigateToURL() is to open the webbrowser, as stated in its documentation:
Opens or replaces a window in the application that contains the Flash Player container (usually a browser). In Adobe AIR, the function opens a URL in the default system web browser
In order to perform an request (without opening a browser, just the HTTP communication) you should use URLLoader.
The URLLoader class downloads data from a URL as text, binary data, or URL-encoded variables.
On a related note: your logic is not valid. The call to a server is asynchronous. You have to wait for the response to be returned before reasoning about the result.
The URLLoader class dispatches a number of Events that help you decide when the result of a request is returned or if there's a problem with it.

ActionScript 3: Error when try execute bitmap.draw();

I'm creating a app in flash AS3, that make a snapshop from a movieClip (e.g. image) and send data to server (data is received with PHP). So, when app is executed on flash, the RAW data is sent to server and my file image is created. But, when i put flash Movie on HTML Source, and try execute on browser, the movie is loaded, but the action that is sending image to the server is not running.
Below is my code:
var jpgSource:BitmapData = new BitmapData( 600, 600 );
jpgSource.draw(image); // <--- PROBLEM!!!
// encode it to jpeg and convert it to byte array
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
var request:URLRequest = new URLRequest("./post-image?facebookID="+user.facebook.id);
request.requestHeaders.push(new URLRequestHeader("Content-type", "application/octet-stream"));
request.method = URLRequestMethod.POST;
request.data = jpgStream;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent){
trace(e.status);
ExternalInterface.call("console.log","Request Response Status: " + e.text);
//ExternalInterface.call("console.log",e);
}, false, 0, true);
loader.addEventListener(Event.COMPLETE, function(e:Event){
trace( new String(loader.data));
ExternalInterface.call("console.log",new String(loader.data));
}, false, 0, true);
loader.load(request);
Does anyone know what might be happening?
Thanks!
My guess is that flash (in the browser) is blocking the request due to security issues, especially if you are running that file locally. Try running it from the same server that is running the PHP and see if that helps. You could also go into the flash settings on your computer and add the swf folder as a trusted location. The flash IDE has different sandbox restrictions than flash in the browser. You also might try flashbug in firefox to see if you could display the error you are getting. Hope this helps.

How post extra name value pairs with a binary data post in AS3?

Here I upload recorded sound to server, but I need to add file name and the user name who is uploading the file. But I don't know how I can to post extra name value pairs with a binary data post?
function onClick(e:MouseEvent)
{
var sba:ByteArray = mp3Encoder.mp3Data;
var req:URLRequest = new URLRequest(URL);
req.contentType = 'application/octet-stream';
req.method = URLRequestMethod.POST;
req.data = sba;
var loader:URLLoader = new URLLoader();
loader.addEventListener( ProgressEvent.PROGRESS, progressHandler );
loader.addEventListener( Event.COMPLETE, completeHandler );
loader.load( req );
}
To do something like that you're likely going to have to use a URLRequest header, check out this information here:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequestHeader.html
You can use multipart request for sending both types of data (binary and variables). Check out this answer about how to create it in AS3:
Send file from actionscript to servlet

AS3 AIR URLLoader POST

I am developing my first AIR app (moving over from PHP/Javascript) and am at a stage where I want to send some data from the app back to a PHP script on my server. I have the following:
var url:String = "PHP URL HERE";
var request:URLRequest = new URLRequest(url);
var requestVars:URLVariables = new URLVariables();
requestVars.test = "1234";
request.data = requestVars;
request.method = URLRequestMethod.POST;
request.contentType = "application/xml;charset=utf-8";
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, processSERPS, false, 0, true);
urlLoader.load(request);
I did have something else in the server side PHP script originally but for debugging I just changed it to dump the REQUEST array.
With the code above it will simply return nothing:
Array
(
)
But if I change the request method to Get:
request.method = URLRequestMethod.GET;
I receive:
Array
(
[test] => 1234
)
Which tells me that the code is correct, it just isn't sending the post parameters for some reason.
I would just alter the code to use GET variables but unfortunately the data I need to send is too large hence the need for POST.
Any help appreciated!
For URLRequest.contentType:
If the value of the data property is a URLVariables object, the value
of contentType must be application/x-www-form-urlencoded.
This is the default value, so just removing your assignment should do it.

How do I send a bytearray to server and detect progress?

I am using Flash runtime (flash player 10). I have a flv encoded bytearray which I need to send to the server( simple php, no FMS or socket servers) and save there. I can use the urlLoader and post everything but then i won't get the progress percentage, so instead I tried saving it with a file reference like this:
var url_ref:URLRequest = new URLRequest("save_vid.php");
url_ref.contentType = "multipart/form-data; boundary="+getBoundary();
url_ref.data = _baFlvEncoder.byteArray;
url_ref.method = URLRequestMethod.POST;
var upfileRef:FileReference = new FileReference();
upfileRef.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
upfileRef.addEventListener(Event.COMPLETE, videoUploadComplete);
upfileRef.upload(url_ref);
But when I try this, I am getting an error:
Error #2037: Functions called in incorrect sequence, or earlier call was unsuccessful.
Any idea how I can do this?
Try this:
var vars :URLVariables = new URLVariables();
vars.bytearray = _baFlvEncoder.byteArray;
var req :URLRequest = new URLRequest("save_vid.php");
req.method = URLRequestMethod.POST;
req.data = vars;
var ldr :URLLoader = new URLLoader();
ldr.addEventListener( Event.COMPLETE, onLoaded );
ldr.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
ldr.addEventListener( ProgressEvent.PROGRESS, onProgress );
ldr.load( req );
function onProgress( e:ProgressEvent ):void
{
trace( "Progress: " + e.bytesLoaded / e.bytesTotal );
}
and in PHP
$bytearray = $_POST['bytearray']