Ruby - Uploading a file using RestClient post

2019-07-24 02:36发布

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条回答
Anthone
2楼-- · 2019-07-24 03:14

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!

查看更多
登录 后发表回答