Flex 3: Upload multiple files via POST with AS3

Published by cybso on
This is a post from my original site, which was hosted by the former blog service of the University of Osnabrück. I have moved it to the new site for archiving. Pages linked in this article may no longer work today, and the blog comments under the article no longer exist. Opinions expressed in this article reflect the point of view of the time of publication and do not necessarily reflect my opinion today.

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()
  1. Add your parameters and file attachments
postData.addParameter('foo1', 'bar1'); // POST-Field 'foo1' has value 'bar1'
postData.addParameter('foo2', 'bar2'); // POST-Field 'foo2' has value 'bar2'

// POST-Field 'uploadedFile1' contains someBinaryData1 (ByteArray)
// as 'application/octet-stream' with filename 'uploadedFile1'
postData.addFile('uploadedFile1', someBinaryData1);

// POST-Field 'uploadedFile2' contains someBinaryData2 (ByteArray)
// as 'image/png' with filename 'image.png'
postData.addFile('uploadedFile2', someBinaryData2, 'image.png', 'image/png')
  1. Close this object. This will append the ending boundary to the data which makes it impossible to add additional form data.
postData.close();
  1. Bind this to an URLRequest
var request:URLRequest = new URLRequest("http://www.example.org/someDestination/");
postData.bind(request)
  1. Send the request
var urlLoader:URLLoader = new URLLoader();
urlLoader.load(request);

Have fun!