AS3:How display ByteArray upload percentage? - php

I have used ShineMP3 to record sound. Now I'm trying to upload the mp3 file to server. Here is my AS3 code:
function onWavClick(e:MouseEvent)
{
var sba:ByteArray = mp3Encoder.mp3Data;
var req:URLRequest = new URLRequest('http://localhost/upload.php');
req.contentType = 'application/octet-stream';
req.method = URLRequestMethod.POST;
req.data = sba;
var loader:URLLoader = new URLLoader(req);
}
How can I display a percentage of upload, and if it was complete and successfully go to next frame?
Thanks.

Instead of passing the URLRequest in the constructor of your URLLoader, use the URLLoader's load() method. There really is no occasion you should pass the request through the constructor, as it starts the request immediately and can complete before you are able to attach an event listener at times. Always follow this process:
Instantiate URLLoader and URLRequest
Attach event listeners and set properties on both
Call load() using the URLRequest
This will allow you to attach a ProgressEvent event of type PROGRESS, which will include a bytesTotal and a bytesLoaded property when it is dispatched. You can use these to display the percentage however you want. You can also attach Event.COMPLETE, which will fire when the upload is finished.
function onWavClick(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 );
}
function progressHandler( e:ProgressEvent ):void {
trace( e.bytesLoaded / e.bytesTotal ); // output: progress, as a decimal from 0 to 1
}
function completeHandler( Event ):void {
// download/upload is complete
}

One suggestion could be this PHP Upload Progress bar:
http://www.johnboyproductions.com/php-upload-progress-bar/

Related

Upload bitmap data from flash to laravel route

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.

AS3. Unable to connect SWF with PHP in order to process a flashvar

here 5:44 am , all night up trying to make this work.
Im trying to send a URL from a swf file to a php file, process that URL with the php code and return it to the swf.
I succeeded on sending and procesing the data. The problem arrives when I try to use the data on the actionScript code.
//videoSrc is a string containing the URL I want to process.
videoSrc=modifySrc(videoSrc);
function modifySrc(vSrc:String):String{
// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
// Be sure you place the proper location reference to your PHP config file here
var varSend:URLRequest = new URLRequest("http://foo.net/config_flash.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);
variables.uname = vSrc;
variables.sendRequest = "parse";
// Send the data to the php file
varLoader.load(varSend);
// the php function ends with ' print "var1=$UrlProcessed"
function completeHandler(event:Event):void{
vSrc = event.target.data.var1;
}
return vSrc;
}
The problem is that vSrc never changes. I think the problem is related to this line:
varLoader.addEventListener(Event.COMPLETE, completeHandler);
I'm not being able to make completeHandler modify vSrc value.
That's because network requests are asynchronous. The return value from modifySrc remains unchanged while the function is executing. It only changes when the URLLoader instance triggers a Event.COMPLETE event. Try this instead:
modifySrc(videoSrc);
function modifySrc(src:String):void
{
...
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, modify_completeHandler);
...
}
function modify_completeHandler(event:Event):void
{
var loader:URLLoader = event.target as URLLoader;
loader.removeEventListener(Event.COMPLETE, modify_completeHandler);
videoSrc = loader.data.var1;
}
I've truncated the rest of your initialization code from modifySrc for brevity.

How do i POST a variable value to a php file?

i need to send a variable value from a simple flash program to a php file or my database, i found this code online for that
var loader:URLLoader = new URLLoader();
loader.addEventListener( Event.COMPLETE, completeHandler );
var variables:URLVariables = new URLVariables();
variables.someVar = "someValue";
var request:URLRequest = new URLRequest("myPhpPage.php");
request.method = URLRequestMethod.POST;
request.data = variables
loader.load(request);
function completeHandler( event : Event ) : void{
trace( "finished sending and loading" );
}
but if i make a simple program with one button which raises the value or 'p' by one for every click with the code
on (press) {
i ++;
}
and i put that code for post in the frame actions window i get error messages. One of them is 'The class or identifier 'URLLoader' could not be loaded.' i also can't load URLVariables , Events and URLRequest. Please tell me what i am missing here.
Make sure you have the proper imports to use the classes such as URLLoader and URLVariables. Check adobe site to see what package they come from
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html
We see that they all come from the flash.net package. You would want to make sure to import the package like so:
import flash.net.*;

Loading files with extension data from POST send - php as3

I'm trying to work out from an old as2 tutorial how to amend a script for as3/php eCard system for a business card but I can't find reference anywhere to how you'd do the following :
AS2 :
loadVariablesNum ("http://www.theSite.com/Cards/bCard/"+BcardText+".txt", 0);
AS3 :
// setup URLLoader
var loader:URLLoader = new URLLoader;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
// event listener for function when loaded
loader.addEventListener(Event.COMPLETE, varsLoaded);
// file URLRequest
loader.load(new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt"));
// set the variables from the data.txt file
function varsLoaded (event:Event):void {
//Load Data
cName.text = loader.data.cName;
cDescription.text = loader.data.cDescription;
}
With this it kicks out the following error message :
Error opening URL 'http://www.theSite.com/Cards/bCard/undefined.txt'
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables()
at flash.net::URLLoader/onComplete()
I can't work out where or how you define the +BcardText+ for it to pull it in.
Any help would be gratefully received.
I'm not sure If I'm even close as its from as2, it seems the logical approach for loading it but I've not dealt with external files having parameters before.
Thanks in advance if anyone can help out in anyway!
NEW LOADER - FIXED!!!
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt");
loader.load(request);
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loaderIOErrorHandler);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function loaderIOErrorHandler(event:IOErrorEvent):void{
trace("ioErrorHandler: " + event);
}
// set the variables from the .txt file
function completeHandler (event:Event):void {
//trace("Content: " + loader.data);
this.Variable1.text = loader.data.Variable1; //Whatever dataField1 you saved as
this.Variable2.text = loader.data.Variable2; //Whatever dataField2 you saved as
}
Then you just setup FlashVars to distinguish the +BcardText variable in the loader prior to committing it!
BcardText was a variable defined in the as2 project. Look around (maybe on previous frames?) and you should find where it got declared. It looks like an ID to represent the card. So each card has a unique file 12345.txt, 09876.txt etc.
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt");
loader.load(request);
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loaderIOErrorHandler);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function loaderIOErrorHandler(event:IOErrorEvent):void{
trace("ioErrorHandler: " + event);
}
// set the variables from the .txt file
function completeHandler (event:Event):void {
//trace("Content: " + loader.data);
this.Variable1.text = loader.data.Variable1; //Whatever dataField1 you saved as
this.Variable2.text = loader.data.Variable2; //Whatever dataField2 you saved as
}
Then you just setup FlashVars to distinguish the +BcardText variable in the loader prior to committing it!
Have scoured the Internet and gone half mad working this out but finally chuffed to say I broke it's back...!
A big thanks for helping point me in the right direction guys. #Jason #Eugen
Θ)

Passing Variables from Flash to PHP

Creating a flash project where users can visit the site, and turn off/on objects in a house (ie. lights, tv, computer, etc.) The next user who will visit the house in the website, will see what lights or house appliances were left on. Flash variables are passed to PHP, and those variables are saved in an XML file. (For testing to see what is being saved to the XML file, on each click --vars.xml opens.) In the vars.xml file, I see that the house objects that were last turned on--are saved in the XML file--BUT in the SWF file, ONLY one of the objects that are listed in the XML are turned ON. Only the last object that was clicked on would show ON--not all the objects in the XML file.)
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.*;
import flash.net.*;
public class House extends MovieClip {
var request:URLRequest = new URLRequest("vars.xml")
var loader:URLLoader = new URLLoader();
// Constructor--------------------------------------------------------------------
public function House()
{
loader.addEventListener(Event.COMPLETE, parseXML);
loader.load(request);
}
// function sendPhp ------------------------------------------------------------------
function sendPhp():void
{
// send vars to php
var request:URLRequest = new URLRequest("write_xml.php"); // the php file to send data to
var variables:URLVariables = new URLVariables(); // create an array of POST vars
for (var i:int=0; i<onList.length; i++) {
variables["v"+i] = onList[i];
}
//variables['powerUsage'] = totalTxt.text;
request.data = variables; // send the vars to the data property of the requested url (our php file)
request.method = URLRequestMethod.POST; // use POST as the send method
try
{
var sender:URLLoader = new URLLoader();
sender.load(request); // load the php file and send it the variable data
navigateToURL(new URLRequest("vars.xml"), '_blank'); //show me the xml
}
catch (e:Error)
{
trace(e); // trace error if there is a problem
}
}
// function parseXML ------------------------------------------------------------------
function parseXML(evt:Event)
{
var xdata:XML = new XML(loader.data); // using E4x
//xdata.child(0);
for (var j:int=0; j<xdata.length(); j++) {
onList[j] = xdata.child(j);
for (var k:int=0; k<HouseObjects.length;k++) {
//root[onList[j]].gotoAndStop(3);
if (onList[j] == HouseObjects[k].name) {
HouseObjects[k].gotoAndStop(3);
//trace("tracing house objects"+ HouseObjects[k]);
trace("onList[j]: " + onList[j]);
trace("Array onList: " + onList);
}
}
}
}
} //end of class
} // end of package
You actually don't need to put all this code here, and it's true that you should make your app more secure , especially after showing all this info! If your XML is not the problem , check the Actionscript part, particularly the parseXML() function.
Are you able to trace the names of the components that are switched on? If yes , concentrate on what's happening in your loop. If your xml is fine, the problem is not passing data from PHP to Flash.
I like the tree house! ;)

Categories