使用HTTParty发送多个文件

Raj*_*hra 7 ruby web-services ruby-on-rails httpclient httparty

这是正在使用的代码 Net::HTTP::Post

request = Net::HTTP::Post.new(url)
...
form_data = [
  ['attachments[]', File.open('file1.txt')],
  ['attachments[]', File.open('file2.txt')]
]
request.set_form form_data, 'multipart/form-data'
http.request(request)
Run Code Online (Sandbox Code Playgroud)

现在,我正在尝试httparty像下面这样使用,但是它不起作用。

body = { attachments: [ File.open('file1.txt'), File.open('file2.txt') ] }

HTTParty.post(url, body: body)
Run Code Online (Sandbox Code Playgroud)

我从Web服务呼叫获得的响应如下:

#<HTTParty::Response:0x557d7b549f90 parsed_response={"error"=>true, "error_code"=>"invalid_attachment", "error_message"=>"Attachmen
t(s) not found or invalid."}, @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"server"=>["nginx"], "date"=>[
"Mon, 20 May 2019 07:41:50 GMT"], "content-type"=>["application/json"], "content-length"=>["102"], "connection"=>["close"], "vary"=>["
Authorization"], "set-cookie"=>["c18664e1c22ce71c0c91742fbeaaa863=uv425hihrbdatsql1udrlbs9as; path=/"], "expires"=>["Thu, 19 Nov 1981
08:52:00 GMT", "-1"], "cache-control"=>["no-store, no-cache, must-revalidate", "private, must-revalidate"], "pragma"=>["no-cache", "no
-cache"], "x-ratelimit-limit"=>["60"], "x-ratelimit-remaining"=>["59"], "strict-transport-security"=>["max-age=63072000; includeSubdom
ains;"]}>
Run Code Online (Sandbox Code Playgroud)

似乎无法读取文件的内容。是否HTTParty支持此功能,或者我需要使用其他宝石?

lac*_*der 0

像这样的东西应该有效,我刚刚测试过,对我来说没问题。

HTTParty.post(url, 
              body: { attachments: [ 
                   File.read('foo.txt'), 
                   File.read('bar.txt')] })
Run Code Online (Sandbox Code Playgroud)