views:

821

answers:

4

Is there any way to upload files from a flex app to a rails 2.2 backend when using the default Cookie Session Store?

A: 

Well, this is something which I'd love to know as well. There are just too many outdated posts and articles hanging around the internet to find a working solution, since Rails is an ever-changing framework... If anyone figures out how to do this, please do give a shout.

Cheers

Attila Györffy
A: 

I would like to know it aswell. Working on that right now.

wallyqs
+1  A: 

No. The reason it doesn't work is because Flex does not transmit the cookies when using FileReference#upload. A workaround (for Rails 2.3) is to insert a custom middleware handler for flash requests that takes arguments in the query string and adds them to the HTTP_COOKIE environment before it reaches Rails.

require 'rack/utils'

class FlashSessionCookieMiddleware
  def initialize(app, session_key = '_session_id')
   @app = app
   @session_key = session_key
  end

  def call(env)
    if env['HTTP_USER_AGENT'] =~ /^(Adobe|Shockwave) Flash/
      params = ::Rack::Utils.parse_query(env['QUERY_STRING'])
      env['HTTP_COOKIE'] = [ @session_key, params[@session_key] ].join('=').freeze unless params[@session_key].nil?
    end
    @app.call(env)
  end
end

Make sure the file is in your load path and add it to your session_store.rb:

ActionController::Dispatcher.middleware.use FlashSessionCookieMiddleware, ActionController::Base.session_options[:key]

Then you'll need to output the session key to a view somewhere and load it using ExternalInterface inside of Flex:

def upload_path_with_session_information
  session_key = ActionController::Base.session_options[:key]
  uploads_path(session_key => cookies[session_key], request_forgery_protection_token => form_authenticity_token)
end

As you can see I have resource called uploads and I use the upload_path_with_session_information helper to give me a nice URL that when POSTED to from FLEX lets you keep your cookie store for everything else.

I honestly don't remember where I found this information online, but I can't take the credit for it. Hope it makes sense for you.

camwest
I just realized you specifically put Rails 2.2 in the topic. Sorry about that.
camwest
A: 

A detailed blog posted on this topic (using rack) is available on:

http://thewebfellas.com/blog/2008/12/22/flash-uploaders-rails-cookie-based-sessions-and-csrf-rack-middleware-to-the-rescue

lordarmitage