I am trying to upload a file to API thr the ‘net/http’ or
‘rest-open-uri’
client,
the code I have done is
require ‘rest-open-uri’
require ‘uri’
require ‘cgi’
require ‘net/http’
require ‘net/https’
require ‘mime/types’
username=“XXXXXXXXXXXXXXXXXXXXXXX”
password=“XXXXXXXXXXXXXXXXXXXXXX”
def form_encoded(hash)
encoded = []
hash.each do |key, value|
encoded << CGI.escape(key) + ‘=’ + CGI.escape(value)
end
return encoded.join(’&’)
end
boundary_token = [Array.new(8) {rand(256)}].join
boundary_marker = “–#{boundary_token}\r\n”
file = File.open(“my_img.jpg”)
filename = File.basename(file.path)
mime_type = MIME::Types.of(filename)
@service_root = “#######################”
representation =
form_encoded({
“Content-Type”=>"#{mime_type}\r\n\r\n#{file.read}\r\n",“Content-Transfer-Encoding”
=> “binary\r\n”, “Content-Disposition”
=> “form-data” , “uploaded_data[filename]”=>"#{filename}"})
puts representation
response = open(@service_root + ‘/file/uploads.xml’, :method
=> :post,:http_basic_authentication => [username,
password],:body=>representation )
puts response.read
The error I am getting is…
from
/lib/ruby/gems/1.8/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:659:in
buffer_open' from /lib/ruby/gems/1.8/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:194:in
open_loop’
from
/lib/ruby/gems/1.8/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:192:in
catch' from /lib/ruby/gems/1.8/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:192:in
open_loop’
from
/lib/ruby/gems/1.8/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:162:in
open_uri' from /lib/ruby/gems/1.8/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:561:in
open’
from
/lib/ruby/gems/1.8/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:35:in
`open’
I am not really sure about the way to be done!
I have referred the urls
http://www.realityforge.org/articles/2006/03/02/upload-a-file-via-post-with-net-http