简体   繁体   English

使用 HTTParty 发送多个文件

[英]Send multiple files using HTTParty

Here is the code which is working using Net::HTTP::Post这是使用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)

Now, I am trying to use httparty like below but it is not working.现在,我正在尝试像下面那样使用httparty ,但它不起作用。

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

HTTParty.post(url, body: body)

The response I am getting from web service call is below:我从网络服务调用得到的响应如下:

#<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;"]}>

It looks like it is not able to read the contents of files.看起来它无法读取文件的内容。 Does HTTParty support this or I need to use some other gem? HTTParty支持这个还是我需要使用其他一些 gem?

Something like this should work, I just tested it, worked for me no problem.这样的东西应该可以工作,我刚刚测试过,对我没问题。

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

With HTTParty you can pass IO/Files as parameters the same way (multipart is automatically set to true if there's a file in parameters).使用 HTTParty,您可以以相同的方式将 IO/Files 作为参数传递(如果参数中有文件,multipart 会自动设置为 true)。

But keep in mind that files should be closed after upload, otherwise you may run out of file descriptors before GC collects them:但请记住,上传后应关闭文件,否则您可能会在 GC 收集它们之前用完文件描述符:

files = ['file1.txt', 'file2.txt'].map{|fname| File.open(fname) }
begin
  HTTParty.post(url, body: { attachments: files })
ensure
  files.each(&:close)
end

That should work for you if net/http variant does (and is actually the same as your code).如果 net/http 变体可以(并且实际上与您的代码相同),那应该对您有用。

Other thing to look at is content type detection by filename - because file upload consists of filename, content type and data itself.其他需要注意的是通过文件名检测内容类型 - 因为文件上传由文件名、内容类型和数据本身组成。 Error 400 with "invalid_attachment" you're getting suggests that more probably it's related to content type or other validation on server side (so make sure you're testing with the same files and nothing else changes other than http lib), also check httparty to be a recent version您收到的带有“invalid_attachment”的错误 400 表明它更有可能与服务器端的内容类型或其他验证有关(因此请确保您正在使用相同的文件进行测试,并且除了 http lib 之外没有其他任何更改),还要检查 httparty是最新版本

I've written a test program which sends the same multipart request using both Net::HTTP and HTTParty .我编写了一个测试程序,它使用Net::HTTPHTTParty发送相同的多部分请求。 Then it compares and prints the request strings so that we can compare them.然后它比较并打印请求字符串,以便我们可以比较它们。 The only substantive difference between the two requests is that HTTParty attempts to guess and set the Content-Type header (eg text/plain for a file named file1.txt ), whereas Net::HTTP always uses application/octet-stream .两个请求之间唯一的实质性区别是 HTTParty 尝试猜测和设置Content-Type标头(例如,名为file1.txt的文件的text/plain ),而 Net::HTTP 始终使用application/octet-stream

HTTParty definitely does read the files and send them in the request. HTTParty 肯定会读取文件并在请求中发送它们。 So, I suggest you investigate if the server is returning an error due to the Content-Type (maybe the content type in your particular request is not supported).因此,我建议您调查服务器是否因Content-Type而返回错误(可能不支持您的特定请求中的内容类型)。

For your reference, here is the test program and specific results .供大家参考,这里是测试程序和具体结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM