The Flex FileReference object makes it very easy to send a file to the server.  I had a situation where I wanted to send some additional data and also get back server output.  This is possible, but not entirely intuitive, so I wanted to document this for others.  In the process of making this work, this post and this post were very helpful to me.

To send more than a file, you use a URLVariables object, like you normally would.  The key is to realize that you also have to set the URLRequest.method to URLRequestMethod.POST, otherwise these variables get lost.  (Makes sense–no one sends files via GET, but it was not obvious to me.)

var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
variables.docname = docName.text;
request.data = variables;
request.method = URLRequestMethod.POST;
try {
fileRef.upload(request);
} catch (error:Error) {
trace("Unable to upload file.");
}

To get any response from the server (like a success message or filename), you have to attach a listener to the DataEvent.UPLOAD_COMPLETE_DATA event, like so:

fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData);

...
private function onUploadCompleteData (event : DataEvent) : void {
var myData = new String(event.data);
// do something with your serverside data...
}

Technorati Tags: ,


© Moore Consulting, 2003-2019