patm
patm

Reputation: 1486

Ruby upload files with a non libcurl library

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

Upvotes: 2

Views: 132

Answers (1)

the Tin Man
the Tin Man

Reputation: 160571

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.

Upvotes: 1

Related Questions