1

I am trying to upload an image. this is the Curl code I received from the documentation of the website

curl -X POST 
    'https://my.craftar.net/api/v0/image/?api_key=123456789abcdefghijk123456789abcdefghijk' 
    -F "item=/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/" 
    -F "file=@test.png"

I tried to solve it with 'net/http/post/multipart'

File.open("./test.png") do |png|
    data = {"item" => "/api/v0/item/2fb8cc16002742ccbbecddc186b1e131"}
    uri = URI.parse('https://my.craftar.net/api/v0/image/?api_key=09d29c3801932aab983892565e731ee3e5c0879e')
    headers = { 'Content-Type' =>'application/json'}
    req = Net::HTTP::Post::Multipart.new uri.request_uri, 
  {"file" => UploadIO.new(png, "image/png", "image.png")}.merge(data),
  headers
  http = Net::HTTP.new(uri.host, uri.port) 
   http.use_ssl = true                      
   res = http.request(req)
   puts "result:"
  puts res.body
end

I based this code on the documentation of 'net/http/post/multipart' But it doesn't work I get a lot of errors. And I can't figure out what I'm doing wrong.

Now I get an error from CraftAR

{"message": "Expected multipart/form-data; boundary=<..> content but got application/json; boundary=-----------RubyMultipartPost.", "code": "WRONG_CONTENT_TYPE"}}

1 Answers1

0

The headers and params are in the wrong order. Consult the source here

The fixed call should be

File.open("./test.png") do |png|
  req = Net::HTTP::Post::Multipart.new(uri.request_uri, 
    {"file" => UploadIO.new(png, "image/png", "image.png")}.merge(data))
  res = Net::HTTP.start(url.host, url.port) do |http|
       http.request(req)
  end
end
Slicedpan
  • 4,995
  • 2
  • 18
  • 33
  • thank you that works better. I do however get an error, but a different one this time: _/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http/generic_request.rb:179:in `send_request_with_body': undefined method `bytesize' for {"item"=>"/api/v0/item/4fe672886ec142f6ab6d72d54acf046f"}:Hash (NoMethodError)_ – Linda de Corte Jul 02 '15 at 13:41
  • Yeah there's another error in the original code, updating now – Slicedpan Jul 02 '15 at 13:56
  • Thank you that helps a lot, changed the code see above. :) – Linda de Corte Jul 03 '15 at 08:01
  • You don't need to set the Content-Type header, the multipart gem does that automatically. Have updated my answer. – Slicedpan Jul 03 '15 at 08:05
  • Yes, I did try that But then I get: {"error": {"code": "VALIDATION_ERROR", "details": {"item": ["This field is required."]}, "message": "Some of the provided fields couldn't be validated. See the 'details' key for more information."}} – Linda de Corte Jul 03 '15 at 08:41
  • Sorry but this has gone way beyond the scope of the original question. I have never used the craftAR API. – Slicedpan Jul 03 '15 at 10:49