Search code examples
ruby-on-railsrubyactiveresourceattachment-fu

What is the best way to upload a file to another Rails application?


I 've researched and noticed that ActiveResource lack this functionality. So, what is the current state of the art when doing a file upload?

One problem with Guillermo's approach is that the request has to be nested, like this:

body = { :file => {:uploaded_data => File.open("#{RAILS_ROOT}/public/tmp/" + original_filename), :owner_id => current_user.owner_id }, :api_key => '123123123123123123'}

Of course it is not possible to do a request like this with HttpClient. I tried other gems I found in github (sevenwire-http-client and technoweenie-rest-client) but they have problems with the file being nested. Is it possible to upload a file with a nested request?


Solution

  • You can try something like the following:

    #I used the HTTPClient gem as suggested (thanks!)
    clnt = HTTPClient.new
    
    # The file to be uploaded is originally on /tmp/ with a filename 'RackMultipart0123456789'. 
    # I had to rename this file, or the resulting uploaded file will keep that filename. 
    # Thus, I copied the file to public/tmp and renamed it to its original_filename.(it will be deleted later on)
    original_filename =  params[:message][:file].original_filename
    directory = "#{RAILS_ROOT}/public/temporary"
    path = File.join(directory, original_filename)
    File.open(path, "w+") { |f| f.write(params[:job_application][:resume].read) }
    
    # I upload the file that is currently on public/tmp and then do the post.
    body = { :uploaded_data => File.open("#{RAILS_ROOT}/public/tmp/" + original_filename), :owner_id => current_user.owner_id}   
    res = clnt.post('http://localhost:3000/files.xml', body)