ActionScript: URL passed into SWF needs to be passed on URLRequest

how do I reference an URL parm passed into the SWF to pass it as a parm to the execution of "save.php"?   can it just be appended to "save.php" in URLRequest or is the use of URLVariables necessary?

function onSaveJPG(e:Event):void{
      var myEncoder:JPGEncoder = new JPGEncoder(100);
      var byteArray:ByteArray = myEncoder.encode(bitmapData);
      
      var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
      
      var saveJPG:URLRequest = new URLRequest("save.php");
      saveJPG.requestHeaders.push(header);
      saveJPG.method = URLRequestMethod.POST;
      saveJPG.data = byteArray;
      
      var urlLoader:URLLoader = new URLLoader();
      urlLoader.addEventListener(Event.COMPLETE, sendComplete);
      urlLoader.load(saveJPG);
      
      function sendComplete(event:Event):void{
            warn.visible = true;
            addChild(warn);
            warn.addEventListener(MouseEvent.MOUSE_DOWN, warnDown);
            warn.buttonMode = true;
      }

}

uberGeekSupremeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

tomaugerdotcomCommented:
Just like you said, add the parms to your URL string "?key1=val1&vey2=val2".

from: http://www.zedia.net/2008/sending-bytearray-and-variables-to-server-side-script-at-the-same-time/
package {
  import flash.display.Sprite;
  import flash.net.URLLoader;
  import flash.net.URLRequest;
  import flash.net.URLRequestMethod;
  import flash.display.BitmapData;
  import flash.utils.ByteArray;
  import com.adobe.images.JPGEncoder;
 
  public class   ByteArrayAndVariableSendExample extends Sprite {
    public function  ByteArrayAndVariableSendExample() {
      var url:String = "http://www.[yourDomain].com/receiveFile.php?exampleSessionId=" + new Date().getTime() + "&exampleUserLabel=guest" ;
 
      var someBitmapData:BitmapData = new BitmapData();//let say we have some bitmapdata
 
      //using the jpeg encoder from the core library
      var jpgEncoder:JPGEncoder = new JPGEncoder(80);
      var myByteArray:ByteArray = jpgEncoder.encode(someBitmapData);
 
      var request:URLRequest = new URLRequest(url);
      request.method = URLRequestMethod.POST;
 
      request.data = myByteArray;
      var loader:URLLoader = new URLLoader();
 
      loader.load(request)
    }
  }
}

Open in new window

0
dgofmanCommented:
Or you can pass parameters in the header that will cach by browser your requests
   var saveJPG:URLRequest = new URLRequest("save.php");
   var variables:URLVariables = new URLVariables();
   variables.key1=val1;
   variables.key2=val2;
   saveJPG.data = variables;
0
uberGeekSupremeAuthor Commented:
looks like you have your own Flash-based camera, eh?  lemme give this some tho and then I'll prolly split the points having the solution a couple different ways.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

tomaugerdotcomCommented:
@dgofman: what happens to the JPEG's ByteArray in your example? Looks like you're only passing the variables but not the actual JPEG data?
0
dgofmanCommented:
I provided example how to pass parameters all other code @uberGeekSupreme: can keep without any changes
0
uberGeekSupremeAuthor Commented:
see this example where I am passing userid into the SWF.  
I don't see how I would reference the inbound URL parm in either of these examples.  please help.


    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="360" height="297">
     <param name="movie" value="Recorder2.swf?userid=<cfoutput>#userid#</cfoutput>" />
     <param name="quality" value="high" />
     <embed src="Recorder2.swf?userid=<cfoutput>#userid#</cfoutput>" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="360" height="297"></embed>
    </object>

0
dgofmanCommented:
You have two optons?
First pass using URL param what you did and another using flashvars. As I already mention advantage your client will cache Recorder2.swf when params will change. In option two is impossible

  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="360" height="297">
     <param name="movie" value="Recorder2.swf"/>
     <param name="quality" value="high" />
     <param name="quality" value="high" />
     <params name="flashvars" value="userid=<cfoutput>#userid#</cfoutput>"/>
     <embed src="Recorder2.swf" flashvars="userid=<cfoutput>#userid#</cfoutput>" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="360" height="297"></embed>
    </object>

 
0
dgofmanCommented:
Sorry is impossible when you are hardcoding URL + &PARAM"
0
uberGeekSupremeAuthor Commented:
a little competition here, eh? @dgofman: where are u seeing hardcoded URL parm?  each time the SWF is invoked the userid will be passed into the SWF anew so I don't understand your concern.
0
dgofmanCommented:
Check your code what you posted

   <param name="movie" value="Recorder2.swf?userid=<cfoutput>#userid#</cfoutput>" />

That means browser will load SWF file by URL:

Recorder2.swf?userid=User1

If you will change userid param to User2 the browser will load again Recorder2.swf file by URL

Recorder2.swf?userid=User2

If you will change you code using flashvars the browser will cache Recorder2.swf and reused SWF file when you will pass User1 and User2
0
dgofmanCommented:
0
uberGeekSupremeAuthor Commented:
I see.  I didn't realize what you meant by "flashvars" but now I get it.  I'll give it a try and let you know.
thanks!
0
tomaugerdotcomCommented:
So in my first example we talk about how to pass parameters AND ByteArray data over to your PHP server-side script. I guess the other piece of the puzzle is how to get those parameters from your host HTML page INTO the SWF in the first place so they can be passed on.

As @dgofman mentions, you'll want to add these parameters as flashvars when you go ahead and embed your flash file into the HTML page. Here's an example where I embed an SWF and pass some parameters to it.

I'm going to pass two parameters: cropMode and quality.

<object id="video"  classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="480" height="307" align="middle">
	<param name="movie" value="saveJPG" />
	<param name="play" value="true" />
	<param name="menu" value="false" />
	<param name="wmode" value="opaque" />
        <param name="flashvars" value="cropMode=scale&quality=high" />
	<!--[if !IE]>-->
	<object type="application/x-shockwave-flash" data="../_resources/videos/mx01_ear-measure.swf" width="480" height="307" align="middle">
		<param name="play" value="true" />
		<param name="menu" value="false" />
		<param name="wmode" value="opaque" />
		<param name="allowFullScreen" value="true" />
                <param name="flashvars" value="cropMode=scale&quality=high" />		
	
		<!--<![endif]-->
		<a href="http://www.adobe.com/go/getflashplayer">Click here to install FlashPlayer for your browser (may require you to restart your browser)</a>
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>[/code

(Note that to accommodate both Explorer and the other browsers, the Embed code is repeated, as are the flashvars!)

So that gets two variable INTO the SWF. Now the SWF needs to read them once it has finished loading. That's easy. Access variables using the root's loaderInfo object:

[code]var swfCropMode:String = this.loaderInfo.parameters['cropMode'];
var swfQuality:String = this.loaderInfo.parameters["quality"];

Open in new window


And that's all there is to it. Now you can use the swfCropMode variable and the swfQualityVariable with the code snipped we had above and you can pass these values on to the server-side PHP image processing app.

Do note that the variable names I'm using, as always, are completely arbitrary. You could have said
var myAwesomeVariableName:String = this.loaderInfo.parameters['cropMode'];

Open in new window


Hope this gets you on the right track.

Good luck!

T
0
tomaugerdotcomCommented:
There's an error in my code above (can't edit it). In the first <object> block I declare the movie name as "saveJPG" (and it should have been "saveJPG.swf", but I forgot to also do the same in the second <object> block: data="saveJPG.swf".

Here's that revised block:

<object id="video"  classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="480" height="307" align="middle">
        <param name="movie" value="saveJPG.swf" />
        <param name="play" value="true" />
        <param name="menu" value="false" />
        <param name="wmode" value="opaque" />
        <param name="flashvars" value="cropMode=scale&quality=high" />
        <!--[if !IE]>-->
        <object type="application/x-shockwave-flash" data="saveJPG.swf" width="480" height="307" align="middle">
                <param name="play" value="true" />
                <param name="menu" value="false" />
                <param name="wmode" value="opaque" />
                <param name="allowFullScreen" value="true" />
                <param name="flashvars" value="cropMode=scale&quality=high" />          
        
                <!--<![endif]-->
                <a href="http://www.adobe.com/go/getflashplayer">Click here to install FlashPlayer for your browser (may require you to restart your browser)</a>
        <!--[if !IE]>-->
        </object>
        <!--<![endif]-->
</object>

Open in new window

0
uberGeekSupremeAuthor Commented:
thanks you guys!  please be patient.  once I try out the code I will award the points.
0
uberGeekSupremeAuthor Commented:
the "photo booth" applet I am using is being invoked like this.  how would I include Flashvars in this situation?  

  <script type="text/javascript">
      var mainswf = new SWFObject("take_picture.swf", "main", "700", "400", "9", "#ffffff");
      mainswf.addParam("scale", "noscale");
      mainswf.addParam("wmode", "window");
      mainswf.addParam("allowFullScreen", "true");
      //mainswf.addVariable("requireLogin", "false");
      mainswf.write("flashArea");
      
  </script>

0
tomaugerdotcomCommented:
uncomment that mainswf.addVariable() bit, and replace the first argument with the name of your variable that you want to have access to in Flash, and replace the second argument with the value of that variable. If you need more than one variable, duplicate that line and just change the arguments.

does that help?
0
dgofmanCommented:
@uberGeekSupreme:

What do you mean:

--the "photo booth" applet I am using is being invoked like this.
0
dgofmanCommented:
Plus be sure you are using correct syntax we have two different versions using SWFObject 1.5 and 2

http://blog.deconcept.com/swfobject/


You can play with this program to get generated script

http://www.zenoplex.jp/tools/swfobject_generator.html
html
0
uberGeekSupremeAuthor Commented:
I've got it figured out for the most part.    all I need know is how to append the URL parm "itemID" onto save.php


      var itemID:String = this.loaderInfo.parameters['itemID'];

      var saveJPG:URLRequest = new URLRequest("save.php");
      saveJPG.requestHeaders.push(header);
      saveJPG.method = URLRequestMethod.POST;
      saveJPG.data = byteArray;
0
uberGeekSupremeAuthor Commented:
sorry to be difficult but ActionScript is a bit cryptic, eh?
0
dgofmanCommented:
     var itemID:String = this.loaderInfo.parameters['itemID'];

      var saveJPG:URLRequest = new URLRequest("save.php");
      saveJPG.requestHeaders.push(header);
      saveJPG.method = URLRequestMethod.POST;

var variables:URLVariables = new URLVariables();
   variables.itemID="My Item ID";
   saveJPG.data = variables;

      saveJPG.data = byteArray;
 
   
0
dgofmanCommented:
comment

//saveJPG.data = byteArray;
0
dgofmanCommented:
Try this:

var itemID:String = this.loaderInfo.parameters['itemID'];

var saveJPG:URLRequest = new URLRequest("save.php");
saveJPG.requestHeaders.push(header);
saveJPG.method = URLRequestMethod.POST;

var variables:URLVariables = new URLVariables();
variables.itemID = itemID;
saveJPG.data = variables;
0
dgofmanCommented:
For example I tryied to send fake request to google :)

var itemID:String = this.loaderInfo.parameters['itemID'];
                  
                  var saveJPG:URLRequest = new URLRequest("http://www.google.com/save.php");
                  saveJPG.method = URLRequestMethod.POST;
                  
                  var variables:URLVariables = new URLVariables();
                  variables.itemID = itemID;
                  saveJPG.data = variables;
                  
                  
                  var loader:URLLoader = new URLLoader();
                  loader.load(saveJPG);

Here is tarce from a FireBug

POST save.php
      
404 Not Found
      
google.com
      
11.5 KB
      
74.125.224.148:80
      
 
100ms
HeadersPostResponseHTML
Parametersapplication/x-www-form-urlencoded
itemID      null
Source
Content-type: application/x-www-form-urlencoded Content-length: 11 itemID=null


So, request with param itemID is working
0
uberGeekSupremeAuthor Commented:
how do I send byteArray (captured photo) and the URL variable saveJPG.data??
0
uberGeekSupremeAuthor Commented:
well, they say it's quite simple but I don't quite get it.  please explain how it is sending both JPG and URL parm...

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);
}
0
dgofmanCommented:
Your flash request is valid modify your PHP script

<?php
$jpg =$GLOBALS["HTTP_RAW_POST_DATA"];

$user = $_GET['user'];
$filename = $user.'.jpg';
file_put_contents($filename, $jpg);
?>
0
uberGeekSupremeAuthor Commented:
how is that different from what I have now??

if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
      $jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
      $img = $_GET["img"];
      $filename = "images/". $_GET['itemID']. ".jpg";
      file_put_contents($filename, $jpg);

0
dgofmanCommented:
How do you know what do you have now you never shared this code :)

Why you are checking img variable
$img = $_GET["img"];

if you are passing "user"

   var request:URLRequest = new URLRequest(ModelLocator.BASE_URL + ModelLocator.UPLOAD_URL + "?user=" + ModelLocator.getInstance().username);
0
uberGeekSupremeAuthor Commented:
again, I am hedphukt by this sort of code.  I haven't dealt with OO code since I was a VB programmer many years ago.  of course, Visual Basic was sort of Object Oriented lite.  B^)

I digress.  I think I've been posting snippets of code from various examples.  my bad.
I'm getting confused between AS & PHP, I think.  :P

here's the complete code I'm working with (AS & PHP)

<<<<<<<ActionScript>>>>>>>>>>>>

function onSaveJPG(e:Event):void{
      var myEncoder:JPGEncoder = new JPGEncoder(100);
      var byteArray:ByteArray = myEncoder.encode(bitmapData);
      
      var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");

      var itemID:String = this.loaderInfo.parameters['itemID'];

      var saveJPG:URLRequest = new URLRequest("save.php");
      var variables:URLVariables = new URLVariables();
            variables.itemID=itemID;
   
      saveJPG.requestHeaders.push(header);
      saveJPG.method = URLRequestMethod.POST;
      saveJPG.data = byteArray;
      
      var urlLoader:URLLoader = new URLLoader();
      urlLoader.addEventListener(Event.COMPLETE, sendComplete);
      urlLoader.load(saveJPG);
      
      function sendComplete(event:Event):void{
            warn.visible = true;
            addChild(warn);
            warn.addEventListener(MouseEvent.MOUSE_DOWN, warnDown);
            warn.buttonMode = true;
      }

}

<<<<<<<PHP>>>>>>>

<?php

if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
      $jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
      $img = $_GET["img"];
      $filename = "images/". $_GET['itemID']. ".jpg";
      file_put_contents($filename, $jpg);
} else{
      echo "Encoded JPEG information not received.";
}
?>


0
dgofmanCommented:
Now, this code working 100%

I tested before to publish

 JPGEncoder.as TestSave.fla save.php
0
dgofmanCommented:
Here is a better test

PHP

<?php

if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
      $jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
      $filename = $_GET['itemID']. ".jpg";
      $file = file_put_contents($filename, $jpg);

      print "http://".$_SERVER['HTTP_HOST']."/$filename";
} else{
      echo "Encoded JPEG information not received.";
}
?>

----------------------------------------------------------------------------------------------------------------------------



var bitmapData:BitmapData = new BitmapData(300, 300, false, 0);
bitmapData.fillRect( new Rectangle(0, 0, 300, 300), 0xFF0000);
                  
var myEncoder:JPGEncoder = new JPGEncoder(100);
var byteArray:ByteArray = myEncoder.encode(bitmapData);

var itemID:String = this.loaderInfo.parameters['itemID'];
if(itemID == null)
      itemID = "DefaultItemId";

var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var saveJPG:URLRequest = new URLRequest("http://localhost/save.php?itemID=" + itemID);
saveJPG.requestHeaders.push(header);
saveJPG.method = URLRequestMethod.POST;
saveJPG.data = byteArray;

var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, sendComplete);
urlLoader.load(saveJPG);

function sendComplete(event:Event):void{
      event.target.removeEventListener(Event.COMPLETE, sendComplete);
      var image:Loader = new Loader();
      image.load(new URLRequest(event.target.data));
      addChild(image);
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
uberGeekSupremeAuthor Commented:
thank you guys for all your help.  now if I can just get the concept of how to pass the JPG *and* parms from AS to PHP I will have created a widget I've been needing for a long while.  
0
dgofmanCommented:
Welcome, can you close this question?
0
uberGeekSupremeAuthor Commented:
please give me some time to try out.  I really don't want to switch to another set of scripts, like you shared here, if I don't have to.  unless they are all set to use exactly as I need them.  B^)

I don't have a way to test locally.  it would be kool if you highlighted the changes.  :)

 is it best to have the full URL starting with HTTP?

***mine***

      function sendComplete(event:Event):void{
            warn.visible = true;
            addChild(warn);
            warn.addEventListener(MouseEvent.MOUSE_DOWN, warnDown);
            warn.buttonMode = true;

***yours (very different)***

function sendComplete(event:Event):void{
      event.target.removeEventListener(Event.COMPLETE, sendComplete);
      var image:Loader = new Loader();
      image.load(new URLRequest(event.target.data));
      addChild(image);


>>> here is a link to what I have so far the only issue is that the "itemID" is not getting passed into "save.php" - the photo ended up being named ".jpg".  :P

http://vutor.com/photo_booth1/

?? is there a way to give you bonus points??

0
dgofmanCommented:
You can assign me extra points if you will split your question to new thread :)
0
uberGeekSupremeAuthor Commented:
kool.  did you get my last question about the sendComplete function you sent being so different than what I have?  now it shows a banner that say "The image is saved. Click here to return." after the photo has been saved and then you click that and it goes to the gallery page.  
in your code it looks like the sendComplete function references itself.  I don't see how it could invoke the warnDown function to navigate to the next page after the whole picture taking & saving process is done.


this comes after the sendComplete function in my code...
function warnDown(e:MouseEvent):void{
      navigateToURL(new URLRequest("images/"), "_blank");
      warn.visible = false;
}

warn.visible = false;
0
uberGeekSupremeAuthor Commented:
ahh, I get it.  yer passing the itemID by appending to "save.php" so the JPG can be passed without conflict of the image being passed, right?  B^)
0
dgofmanCommented:
That what I trying to tell you almost 3 days. You can pass parameters and data from the ActionScript. And I wrote PHP code for testing.
0
uberGeekSupremeAuthor Commented:
sorry, bud, been some crazy times of late.  thanks for your patience.
0
uberGeekSupremeAuthor Commented:
this makes no sense.  I am still getting null itemID passed to save.php

function onSaveJPG(e:Event):void{
      var myEncoder:JPGEncoder = new JPGEncoder(100);
      var byteArray:ByteArray = myEncoder.encode(bitmapData);
      
      var itemID:String = this.loaderInfo.parameters['itemID'];
      if(itemID == null)
      itemID = "0";

      var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
      var saveJPG:URLRequest = new URLRequest("save.php?itemID=" + itemID);
      var variables:URLVariables = new URLVariables();
            variables.itemID=itemID;
   
      saveJPG.requestHeaders.push(header);
      saveJPG.method = URLRequestMethod.POST;
      saveJPG.data = byteArray;
      
      var urlLoader:URLLoader = new URLLoader();
      urlLoader.addEventListener(Event.COMPLETE, sendComplete);
      urlLoader.load(saveJPG);
      
      function sendComplete(event:Event):void{
            warn.visible = true;
            addChild(warn);
            warn.addEventListener(MouseEvent.MOUSE_DOWN, warnDown);
            warn.buttonMode = true;
      }

}

function warnDown(e:MouseEvent):void{
      navigateToURL(new URLRequest("images/"), "_blank");
      warn.visible = false;
}

warn.visible = false;

=============================\
<?php

if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
      $jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
      $img = $_GET["img"];
      $filename = "images/". $_GET['itemID']. ".jpg";
      file_put_contents($filename, $jpg);
} else{
      echo "Encoded JPEG information not received.";
}
?>
0
uberGeekSupremeAuthor Commented:
what about this being passed via javascript invocation?

  <script type="text/javascript">
      var mainswf = new SWFObject("take_picture.swf", "main", "700", "400", "9", "#ffffff");
      mainswf.addParam("scale", "noscale");
      mainswf.addParam("wmode", "window");
      mainswf.addParam("allowFullScreen", "true");
      mainswf.addParam("FlashVars", "itemID=");
      //mainswf.addVariable("requireLogin", "false");
      mainswf.write("flashArea");
      
  </script>

0
uberGeekSupremeAuthor Commented:
it's always something stupid when I get this boggled.   I wasn't passing itemID along the URL string to index.php that invokes the take_picture.swf which is why it is null above.  d'OH!

0
uberGeekSupremeAuthor Commented:
well, I have been resistant to learn ActionScript & PHP partly because they are lame as programming languages go AND they are now sort of tekno fascistically being pushed upon us all.   well, I've been an application programmer since 7/11/77 and always wanted to use the latest & greatest that was easy to use.  I was an RPG programmer for several years.
I digress.   I hate feeling stupid so gotta make up a story about why and wherefor I malfunctioned.  

my bad.   (have ya ever just noticed that yer trying to do it the hard way for no appearent reason??)
0
tomaugerdotcomCommented:
Happens to all of us with new languages / frameworks. AS is actually an awesome language once you get used to it. PHP is a pain in the neck, I'll agree with you there! Good luck.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Adobe Flash

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.