Aug 17
Simple Ruby script for uploading files from Flex
Here is the AS3:
private var fileRef:FileReference = new FileReference();
private function uploadFile():void
{
 fileRef.addEventListener(Event.SELECT, selectHandler);
 fileRef.addEventListener(Event.COMPLETE, completeHandler);Â
try {
     var success:Boolean = fileRef.browse();
 } catch (error:Error) {
     trace("Unable to browse for files.");
  }
}
private function selectHandler(event:Event):void {
   // assumes the Ruby Method is in the application controller
   var request:URLRequest = new URLRequest("application/upload_file")
   try {
       fileRef.upload(request);
   } catch (error:Error) {
       trace("Unable to upload file.");
   }
}
private function completeHandler(event:Event):void {
 fileRef.removeEventListener(Event.SELECT, selectHandler);
 fileRef.removeEventListener(Event.COMPLETE, completeHandler);
 trace("uploaded");
}Â
 Â
Here is the Ruby:
   def upload_file
     file_data = params[:Filedata]
     file_name = params[:Filename].to_s
     File.open(file_name, "wb") { |f| f.write(file_data.read) })
     render(:xml => "< success />" )
   end
That’s it. Note, that if your running on a non-windows box you should change “wb” to “w”.

November 7th, 2006 at 5:02 pm
how would you do this to handle multiple file uploads? i’m new to ruby, but i’m amazed already.
November 7th, 2006 at 7:07 pm
Hi Anthony,
Check out the following tutorial by Kreek at Vixioms Axioms:
http://blog.vixiom.com/2006/09/08/multiple-file-upload-with-flash-and-ruby-on-rails/