Ruby-使用RestClient发布上传文件

问题描述:

我有一个要转换为Ruby的cURL。

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

cURL是这样的:

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

我的Ruby代码是这样的:

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'})

Ruby代码给了我一个400错误的请求。授权或其他标题都没有问题。我认为问题在于将--data-binary转换为Ruby。

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.

任何帮助表示赞赏。

谢谢,
Adrian

Thanks, Adrian

有些事情可能会引起问题。

There are a few things which might cause the problem.


  1. 您要对 RestClient 使用实际的 File 对象,因此请使用 File.open ;。

  2. 您在请求中两次包含了图像对象;您的问题不清楚实际内容。例如,您正在将有效负载元素与标头混合在一起。基于 RestClient.post 的签名,该签名接受参数 url,payload,headers = {} ,您的请求应采取以下两种形式之一:

  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:

技术1::有效负载包含一个名为 upload的字段或参数,并且该值设置为图片对象

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:

技术2:图像文件对象作为唯一的有效载荷发送

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',
)

请注意,我没有包含内容长度 c>标头;使用 RestClient 时通常不需要这样做,因为它在处理文件时会为您插入。

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.

还有另一种方法使用 RestClient 发送有效负载

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

请务必通读 github上的官方文档

我也是 RestClient ,因此,如果我在这种情况下错了,请不要太苛刻;我将立即纠正我的任何误解。希望这会有所帮助!

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!