Sending byteArray and variables to server-side script at the same time

While using the URLLoader classyou can send two types of data to the server. You can either send variables through the URLVariables or by giving a ByteArray to the data property of the URLRequest class. Here is how you would send variables:

package {
  import flash.display.Sprite;
  import flash.net.URLLoader;
  import flash.net.URLRequest;
  import flash.net.URLVariables;
 
  public class URLVariablesExample extends Sprite {
    public function URLVariablesExample() {
      var url:String = "http://www.[yourDomain].com/receiveFile.php";
      var request:URLRequest = new URLRequest(url);
      var variables:URLVariables = new URLVariables();
 
      variables.exampleSessionId = new Date().getTime();
      variables.exampleUserLabel = "guest";
 
      request.data = variables;
 
      var loader:URLLoader = new URLLoader();
      loader.load(request)
    }
  }
}

If you wanted to send a ByteArray, let say to save an image made in your flash on the server, here is how you would pass the data (I’m using the coreLib to convert bitmapData to JPG format which will return a ByteArray) :

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 ByteArraySendExample extends Sprite {
    public function  ByteArraySendExample() {
      var url:String = "http://www.[yourDomain].com/receiveFile.php";
      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)
   }
  }
}

The thing is, there is no actual documentation when you want to send both a byteArray and variables. As you can see in the examples, when you send variables, you set the data property of the URLRequest equal the your URLVariables, but when you send a byteArray you also set the data property equal to your byteArray. So you cannot send both type of data at the same time this way. The way I found is actually pretty simple and I don’t why others have not blogged about this (trust me I have looked for this). What you do is you set the data of the URLRequest equal to the byteArray, but you put your variables in the url String of the URLRequest. Here is some code showing it:

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)
    }
  }
}

Then in your server-side script you recover the variables in the query string and the byteArray in the post part. It’s that simple.

, , , , , , ,

  1. #1 by Justin J. Moses - March 25th, 2009 at 20:02

    So simple and I never thought about it :)

    Nice post.

  2. #2 by till - June 9th, 2009 at 07:06

    Thanks for sharing!

  3. #3 by pushpa - June 15th, 2009 at 09:17

    hi

    i am creating a drawing application in as3. i want to send the bitmap as an email attachment. i duno php. can u please provide me with a example and source.

    thanks a lot

  4. #4 by Mike - June 28th, 2009 at 20:02

    Of course! So simple. Thanks for the hint.

  5. #5 by boxbuilder - July 9th, 2009 at 05:02

    ok, but if I need to send variables by POST?

  6. #6 by Veronique - July 16th, 2009 at 18:25

    Thank you for the post. I have been using it for project where I let users upload images. If the images are larger than 1MB, I resize them on the fly using Matrix and load the bytes.
    All of this works. However the URLLoader doesn’t fire up events until after the image is loaded and displays the bytesLoaded and bytesTotal at 2. Any idea why it would do that and how to fix it.
    Thanks.

  7. #7 by aben - September 25th, 2009 at 14:04

    thanks for the post. i tried your code for the one where it sends a bytearray. but nothing seems to happen. heres my flex side….

    var bitmapData:BitmapData = new BitmapData(txt.width, txt.height);
    bitmapData.draw(txt);
    var jpg:JPEGEncoder = new JPEGEncoder();
    var byteArray:ByteArray = jpg.encode(bitmapData);

    var request:URLRequest = new URLRequest(“http://[xxxxx]/Uploader.ashx”);
    request.method = URLRequestMethod.POST;
    request.data = byteArray;

    var loader:URLLoader = new URLLoader();
    loader.load(request);
    return;

  8. #8 by sungchul - November 13th, 2009 at 05:25

    hi.. thanks for sharing..

    how to get byteArray data in server-side-script.
    it has no variable name… ^^..

  9. #9 by Michael - December 1st, 2009 at 12:50

    do you have an example of the server-side script involved?

  10. #10 by Paulo - March 1st, 2010 at 05:53

    @ Michael
    Hi Michael

    Here’s what I do to get the byteArray from server side in Java, with a servlet. This actually works, unless I missed something on the editing here.

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType(“text/plain”);
    //response.setContentType(“APPLICATION/OCTET-STREAM”);
    PrintWriter out = response.getWriter();

    ServletInputStream servletInput = request.getInputStream();

    int size = request.getContentLength();
    byte[] bytes = new byte[size];

    //here the read method reads the stream and writes to the given byte[]
    servletInput.read(bytes);

    //this function just writes the byte[] it into a file, you can do whatever with the bytes, this is just an example.
    saveToFile(filename,bytes);

    //should send something relevant, back to the response
    out.print(filename);
    out.flush();
    out.close();
    }

  11. #11 by Paulo - March 1st, 2010 at 07:12

    Thanks a lot. works like a charm, so damn simple, hehe.

    I just needed to add to the previous code before the “saveToFile(filename, bytes); :

    “String filename = request.getParameter(“filename”);”
    for getting the filename parameter for example :D

  12. #12 by Guilherme - March 18th, 2010 at 14:38

    @Paulo

    Hi, my image is been cutted in the midle when I use this code to create it from byte array:

    InputStream in = new ByteArrayInputStream(bytes);
    BufferedImage bImageFromConvert = ImageIO.read(in);
    ImageIO.write(bImageFromConvert, “jpg”, new File(“c:\\mypic_new.jpg”));

    Can help me to solve it ?

  13. #13 by Guilherem - March 19th, 2010 at 07:27

    File filename = new File(“C://a.jpg”);
    FileOutputStream out = new FileOutputStream(filename);
    InputStream in = req.getInputStream();

    byte[] buf = new byte[512];
    int nread = 0, total_read = 0;

    while (-1 != (nread = in.read(buf))) {
    total_read += nread;
    out.write(buf, 0, nread);
    }
    out.close();
    in.close();

  14. #14 by Guilherem - March 19th, 2010 at 07:55

    The post above is the way I use to solve the problem. Just use ServletInputStream don’t solve the problem.

    You must pass the req.getInputStream() to the InpuStream and write the FileOutputStream.

    Thanks.

  15. #15 by ratdoghippy - March 22nd, 2010 at 23:20

    can this be used to send the image using PHP to a email address

  16. #16 by Cechise - April 20th, 2010 at 14:22

    Correct me if im wrong, but:

    If you would like to send both variables and the byteArray width post I belive you could simply bas64 encode the bytearray and send it as a variable.

  17. #17 by soft - April 23rd, 2010 at 17:50

    Very good script

  18. #18 by Laxman - May 7th, 2010 at 09:12

    Yes, this trick is very good for a “GET” method. What about, if we have to “POST” the extra variables.
    Like if we need to send ‘password’ variable, it surely wont look good in the url. And also this “GET” method has it own limitation.

    :)

  19. #19 by b - May 7th, 2010 at 10:04

    Cechise is right. I successfully sent an image and other form data using URLVariables by using the ImageSnaphot.encodeImageAsBase64 method.

  20. #20 by dinamicsoft - May 15th, 2010 at 04:42

    how to get byteArray data in server-side-script.
    it has no variable name…

  21. #21 by burzaone - June 29th, 2010 at 14:01

    @ dinamicsoft
    In PHP u can use:

  22. #22 by burr - November 2nd, 2010 at 12:46

    does anyone have the php side for this script?

  23. #23 by GT - December 15th, 2010 at 03:39

    How can send a byteArray formated in FLV instead? Is there also FLVEncoder like JPEGEncoder

  24. #24 by rule - January 31st, 2011 at 07:25

    @pushpa
    same here…
    can u please provide me with a example and source?

    thanks.

  25. #25 by Lotus - May 20th, 2011 at 08:02

    The trick is very good but what if you MUST receive echo from PHP too?

  26. #26 by cpayen - October 5th, 2011 at 11:13

    @burr
    You can use $data = file_get_contents(“php://input”);
    It works fine for me.

  27. #27 by Atari - November 3rd, 2011 at 12:12

    @all
    I combined a multiple FILES & POST send earlier this year, but need it on another project today & had to refresh my memory, and thus came across this post & thought I could offer an option.
    Trick is to manually construct the request as a ByteArray that a URLRequest can consume.
    The whole process is really well documented @ http://marstonstudio.com/2007/10/19/how-to-take-a-snapshot-of-a-flash-movie-and-automatically-upload-the-jpg-to-a-server-in-three-easy-steps/ – along with an UploadHelperClass which creates the scaffold, so you don’t have to ;)
    The class can be hacked to “wrap” & upload multiple files also.
    a.)

  28. #28 by Manel - January 4th, 2012 at 06:00

    @Paulo
    Hello, do you have the server-side code in C#? I’m trying to translate but I can’t.
    Thank you

  29. #29 by Rey - January 28th, 2012 at 13:14

    How i can send byte array and some variables in post

  30. #30 by joana - March 18th, 2012 at 00:05

    hi can you please send me a source file of the .fla and the php server side scripting i cant seem to make it work.. please?

  31. #31 by Tim - August 1st, 2012 at 09:15

    Thanks, bro! Helped me!

  32. #32 by Pranav - August 7th, 2012 at 05:38

    Hi ,can anyone send the php server side script for the same Actionscript ?

(will not be published)
Subscribe to comments feed