Ruby - Uploading a file using RestClient post

寵の児 提交于 2020-01-14 19:56:08

问题


I have a cURL that I am trying to translate into Ruby.

the cURL is this:

curl -i -k -H "Accept: application/json" -H "Authorization: token" -H "Content-Type: image/jpeg" -H "Content-Length: 44062" --data-binary "gullfoss.jpg" http://www.someurl.com/objects

My Ruby code is this:

image = File.read('uploads/images/gullfoss.jpg')
result = RestClient.post('http://www.someurl.com/objects',image,{'upload' => image, 'Accept' => 'application/json', 'Authorization' => 'token', 'Content-Type' => 'image/jpeg', 'Content-Length' => '44062'})

The Ruby code is giving me back a 400 Bad Request. It's not a problem with Authorization or the other headers. I think the problem lies with translating --data-binary to Ruby.

Any help appreciated.

Thanks, Adrian


回答1:


There are a few things which might cause the problem.

  1. You want to use an actual File object with RestClient, so use File.open; it returns a file object.
  2. You are including the image object twice in your request; the actual content is not made clear from your question. You are mixing payload elements with headers, for instance. Based on the signature of RestClient.post, which takes arguments url, payload, headers={}, your request should take one of the two following forms:

Is the endpoint expecting named parameters? If so then use the following:

Technique 1: the payload includes a field or parameter named 'upload' and the value is set to the image object

result = RestClient.post(
  'http://www.someurl.com/objects',
  { 'upload' => image },
  'Accept' => 'application/json',
  'Authorization' => 'token',
  'Content-Type' => 'image/jpeg',
)

Is the endpoint expecting a simple file upload? If so then use:

Technique 2: the image file object is sent as the sole payload

result = RestClient.post(
  'http://www.someurl.com/objects',
  image,
  'Accept' => 'application/json',
  'Authorization' => 'token',
  'Content-Type' => 'image/jpeg',
)

Note that I didn't include the 'Content-Length' header; this is not usually required when using RestClient because it inserts it for you when processing files.

There is another way to send payloads with RestClient explained here.

Make sure to read through the official docs on github as well.

I am also new to RestClient so if I'm wrong in this case don't be too harsh; I will correct any misconceptions of mine immediately. Hope this helps!



来源:https://stackoverflow.com/questions/10687120/ruby-uploading-a-file-using-restclient-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!