0

On a ruby project I am trying to send a image to a server listening to POSTS requests. I would like to avoid using extra necessary gems. I am using ruby 1.9.3 and net/http Multiport is not supported by the server and the following code:

require 'net/http'  
require "uri"

image = File.open(image.path, 'r')

url = URI("http://someserver/#{image_name}")
req = Net::HTTP.new(url.host, url.port)
Net::HTTP.new(url.host, url.port)
headers = {"X-ClientId" => client_id, "X-ClientSecret" => client_secret, "Content-Type" => "image/jpeg"}
response, body = req.post(url.path, image, headers)

crashes with the following error message:

http.rb:1932:in `send_request_with_body': undefined method `bytesize' for #<File:0x007ffdcd335270> (NoMethodError)

While the following succeed in bash:

curl -i -X POST --data-binary @./output.jpg -H 'X-ClientId: ##..##' -H 'X-ClientSecret: ##..##' http:/someserver/output.jpg

Any idea what is going wrong?

Thanks in advance

  • 2
    Read the file into a string, don't try and send the File instance. `post(url.path, image.read, headers)` better yet dont open a file and not close it. `image = File.read('image_path.jpg')` – Lee Jarvis Dec 05 '12 at 12:24

1 Answers1

0

Go through this for ruby script- http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

OR
And for rails you can use 'httmultiparty'.
Go through this - https://github.com/jwagener/httmultiparty

Here is example you can do -

In your controller method just add -

class SomeController <  ApplicationController
   def send_file
       response = Foo.post('/', :query => {
                  :file => File.new('abc.txt') 
       })
       # here Foo is class_name which is present in model/foo.rb
       response.code # it give response code success or failure.
   end
end

In model just make any file, let foo.rb and add following code -

require 'httmultiparty'
class Foo
   include HTTMultiParty
   base_uri 'my/path' #url where to send file 
end  

You will get file on your path by just doing params[:file] . I think this help you.

Sandip Karanjekar
  • 850
  • 1
  • 6
  • 23