views:

456

answers:

2

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?

+2  A: 

The Httpclient gem allows you to do multipart posts like this:

clnt = HTTPClient.new
File.open('/tmp/post_data') do |file|
   body = { 'upload' => file, 'user' => 'nahi' }
   res = clnt.post(uri, body)
 end

You could use this to simply post a file on the local file system to a controller in the other application. If you want to upload data just upload with a form into your app without storing it first, you could probably use the uploaded data from your params immediately in the post body.

Arthur
Thanks for your comment. I wanted to create some discussion regarding this, but it seems almost no one is interested :(
wallyqs
@Arthur After installing HTTPClient gem i am getting this error. NameError (uninitialized constant ClientDocumentsController::HTTPClient): on this line clnt = HTTPClient.new
krunal shah
A: 

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)
Guillermo Romero
@Guillermmo After installing HTTPClient gem i am getting this error. NameError (uninitialized constant ClientDocumentsController::HTTPClient): on this line clnt = HTTPClient.new
krunal shah