我无法影响的协议的网站向我发送POST请求,其中多个参数的名称为“t”。
这是我的request.raw_post
:
--===13978193024621189109088990673===
Content-Disposition: form-data; name="t"
Content-Type: text/plain; charset=UTF-8
thevalue1
--===13978193024621189109088990673===
Content-Disposition: form-data; name="t"
Content-Type: text/plain; charset=UTF-8
thevalue2
--===13978193024621189109088990673===
Content-Disposition: form-data; name="t"
Content-Type: text/plain; charset=UTF-8
thevalue3
--===13978193024621189109088990673===
Content-Disposition: form-data; name="t"
Content-Type: text/plain; charset=UTF-8
thevalue4
--===13978193024621189109088990673===
Content-Disposition: form-data; name="t"
Content-Type: text/plain; charset=UTF-8
thevalue5
--===13978193024621189109088990673===
Content-Disposition: form-data; name="t"
Content-Type: text/plain; charset=UTF-8
thevalue6
标准params
集合仅列出最后一个参数。
如何获取所有值?
重现此请求的方法是:
<form action="/updateinfo" method="post" enctype="multipart/form-data">
<input type="text" name="t" value="thevalue1"><br>
<input type="text" name="t" value="thevalue2"><br>
<input type="text" name="t" value="thevalue3"><br>
<input type="text" name="t" value="thevalue4"><br>
<input type="text" name="t" value="thevalue5"><br>
<input type="text" name="t" value="thevalue6"><br>
<input type="submit">
</form>
答案 0 :(得分:4)
最后我发现并使用了multipart-parser
gem。它缺少文档,所以这里是我使用的代码:
require 'multipart_parser/reader'
module MultiParams
def parse_multi_params(request)
parts={}
reader = MultipartParser::Reader.new(MultipartParser::Reader::extract_boundary_value(request.headers['CONTENT_TYPE']))
reader.on_part do |part|
pn = part.name.to_sym
part.on_data do |partial_data|
if parts[pn].nil?
parts[pn] = partial_data
else
parts[pn] = [parts[pn]] unless parts[pn].kind_of?(Array)
parts[pn] << partial_data
end
end
end
reader.write request.raw_post
reader.ended? or raise Exception, 'truncated multipart message'
parts
end
end
控制器中的用法:
require 'multi_params'
class MyController < ApplicationController
include MultiParams
def my_method
mp = parse_multi_params(request)
process_params(mp[:t])
end
end
答案 1 :(得分:0)
请查看how rack parses incoming parameters并转换为哈希值。您可以使用raw_request
并将其放入您自己的params解析器中,该解析器与机架实现非常相似,并且可以将参数t
直接转换为数组。像这样的东西:
def normalize_params(params, name, v = nil)
name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
k = $1 || ''
after = $' || ''
return if k.empty?
if after == "" && k == 't'
params[k] ||= []
params[k] << v
elsif == ""
params[k] = v
elsif after == "[]"
params[k] ||= []
params[k] << v
elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
child_key = $1
params[k] ||= []
if params_hash_type?(params[k].last)
&& !params[k].last.key?(child_key)
normalize_params(params[k].last, child_key, v)
else
params[k] << normalize_params(params.class.new, child_key, v)
end
else
params[k] ||= params.class.new
params[k] = normalize_params(params[k], after, v)
end
return params
end