I’m trying to upload a file through URLLoader in Actionscript 3, I know it’s possible, at least according to the docs, but I can’t figure it. So if anyone has done this before I’d love to know what I’m leaving out, specifically, I’m unsure about URLRequest and its data property. I know that my file’s data should go there, but I’m unsure as to how.
Here’s a very rudimentary form of the code I’m working with:
//===============================================
public function sendRequest():void {
//===============================================
var newFile:FileReference(); //this eventually gets data loaded to it before I make request
var sendForm:URLLoader = new URLLoader();
var urlString:String = "/proposal_request/?";
var header:URLRequestHeader = new URLRequestHeader("Content-Disposition: attache[attachment]; filename=" + newFile.name);
...
...
urlString += "variable=" + instance_name.text;
urlString += "another_variable=" + another_instance_name.text;
...
...
var requester:URLRequest = new URLRequest(urlString);
requester.contentType = "multipart/form-data";
requester.method = URLRequestMethod.POST;
requester.requestHeaders.push(header);
requester.data = newFile; //here's where I'm most confused, should this be encoded?
...
...
sendForm.addEventListener(HTTPStatusEvent.HTTP_STATUS, responseStatus);
sendForm.load(requester);
}
You could always go that way — but you really don’t have to.
The FileReference class provide you an easy way to upload a file: the method upload().
After your FileReference object has some data, simply call upload passing an URLRequest and optionally a datafield string, with some extra information for the server, and a boolean that will (de)activate the test upload: if your file is over 10KB, the flash player will try to send a 0 byte file as a connection test before uploading the real file.
After that you can just listen for progress, complete and uploadDataComplete events to keep track of the upload.
Adobe AS3 Reference on FileReference.upload()