Flex 3: Upload multiple files via POST with AS3

In my current Abobe Flex project, I needed to upload multple generated files and form fields to a server. UploadPostHelper by Jonathan Marston is a great for uploading one file at time, but sadly I couldn't use (or even modify) it - it's licensed under NonCommercial CC, and my project is a commercial one.

So I had to write my own code which I would like to share with other's (dual-licensed under MPL 1.1 and LGPL 2.1).

Usage of HttpPostData-class: <Update April 1st 2010>I had an error in this text for a half year and nobody noticed? Strange...</Update>

  1. Create an Instance of HttpPostData:
    var postData:HttpPostData = new HttpPostData()
  2. Add your parameters and file attachments
    1. postData.addParameter('foo1', 'bar1'); // POST-Field 'foo1' has value 'bar1'
    2. postData.addParameter('foo2', 'bar2'); // POST-Field 'foo2' has value 'bar2'
    3.  
    4. // POST-Field 'uploadedFile1' contains someBinaryData1 (ByteArray)
    5. // as 'application/octet-stream' with filename 'uploadedFile1'
    6. postData.addFile('uploadedFile1', someBinaryData1);
    7.  
    8. // POST-Field 'uploadedFile2' contains someBinaryData2 (ByteArray)
    9. // as 'image/png' with filename 'image.png'
    10. postData.addFile('uploadedFile2', someBinaryData2, 'image.png', 'image/png')
  3. Close this object. This will append the ending boundary to the data which makes it impossible to add additional form data.
    postData.close();
  4. Bind this to an URLRequest
    1. var request:URLRequest = new URLRequest("http://www.example.org/someDestination/");
    2. postData.bind(request)
  5. Send the request
    1. var urlLoader:URLLoader = new URLLoader();
    2. urlLoader.load(request);

Have fun!

Attachment: 

Comments

There is postData.bind(postData);
Should be postData.bind(request);

Btw. Great job :)

Thank you, fixed it!

Hi Roland,
Used your Code and came with the following suggestion for improvement:
in the function addFile:
I added the square brackets to force an array in PHP and use for name a constant like
'Filedata'
str = 'Content-Disposition: form-data; name="' + name + '[]"; filename="' + filename + '"';
in PHP it is now easier to itterate through $_FILES while $_FILES['Filedata'] an array is.
Otherwise you have to know all the name attributes in order to parse $_FILES in php

Thanks for your code!!