2

Out of sheer curiosity, I'm using the following line to upload files to a Sinatra app:

curl -silent --location --upload-file #{file} http://0.0.0.0:3000/sent/

It works like charm. However if I want to use a pure ruby solution like HTTPClient, what would be the code to get the same result? Can you give me an example?

NOTE: I'm not interested in libcurl related solutions. If there's another gem, except HTTPClient that can achieve this in pure ruby please share.

Best Regards

patm
  • 1,420
  • 14
  • 19
  • This question might interest you: http://stackoverflow.com/questions/12097491/uploading-a-file-using-ruby-nethttp-api-to-a-remote-apache-server-failing-with – quandrum Jan 04 '13 at 18:20
  • 1
    The documentation for various Ruby HTTP clients show how to do these things. Did you read through them to check? – the Tin Man Jan 04 '13 at 18:20
  • Yeah, I didn't find any with a real world example @theTinMan – patm Jan 04 '13 at 22:36

1 Answers1

1

Ruby's Net::HTTP allows you to upload files. From the documentation:

uri = URI('http://www.example.com/todo.cgi')
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end

case res
when Net::HTTPSuccess, Net::HTTPRedirection
  # OK
else
  res.value
end

Add the body of your file to the set_form_data hash and you should be on your way.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • Truth I already tried a similar code but doesn't work... Comes up with a 404 error no matter what. Thanks for your time anyway. – patm Jan 04 '13 at 22:55