Nuclear Rooster

10Apr/080

Simple Rails Uploader

Simple Rails Uploader

I was recently trying to implement an upload to Amazon S3, and it wasn't working. I couldn't tell if it was the Flex front end, or the S3 backend, or what, so I decided to Wear my ruby slippers to work, or rather my Rails slippers (so comfy and I just like them so much).

About 15 minutes and 15 lines of code later, I had a rails app running locally which accepted the upload from Flex and logged all the request parameters. I found the Simplest upload that could possibly work in the Rails Cookbook, and a Rails wiki page to that purpose. In the Rails Cookbook, note that you should use params['file'] rather than the oldschool @params['file'].

To get a simple Rails (> 2.0) app for testing the uploads, try this

rails uploader
cd uploader
script/generate controller upload

Paste in some code from the Simplest Upload Possible article above.

class UploadController < ApplicationController
  def save_file
    logger.info(params.insect)

    if request.get?
    render :text => 'Please Upoad file'
    else
      # Use "wb" mode on windows.
      File.open("#{RAILS_ROOT}/public/files/#{Time.now.to_i}.jpg", "w") do |f|
        f.write(params['file'].read)
      end
    render :text => 'Done'
    end
  end
end

Now, in Flex, have your FileReference upload to your server, and make sure to use the right field name.

[ActionScript]
var urlRequest:URLRequest = new URLRequest("http://127.0.0.1:3000/upload/save_file");
urlRequest.method = URLRequestMethod.POST;
file.upload(urlRequest, "file");
[/ActionScript]

Tails your logs, and look for the output. One step closer.

I might try to clean up a simple uploader app and thow it up (blaagh) here. Any interest?