Skip to content

Commit

Permalink
Support parsing multiple files for one form field
Browse files Browse the repository at this point in the history
  • Loading branch information
timcraft committed Apr 1, 2024
1 parent 8c73aef commit a95077f
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lib/rack/query_parser.rb
Expand Up @@ -132,6 +132,12 @@ def normalize_params(params, name, v, _depth=nil)
if after == ''
if k == '[]' && depth != 0
return [v]
elsif !params[k].nil? && !v.nil? && depth == 0
if params[k].is_a?(Array)
params[k] << v
else
params[k] = [params[k], v]
end
else
params[k] = v
end
Expand Down
16 changes: 16 additions & 0 deletions test/multipart/multiple_files
@@ -0,0 +1,16 @@
--AaB03x
content-disposition: form-data; name="files"; filename="file1.txt"
content-type: text/plain

foo
--AaB03x
content-disposition: form-data; name="files"; filename="file2.txt"
content-type: text/plain

bar
--AaB03x
content-disposition: form-data; name="files"; filename="file3.txt"
content-type: text/plain

quux
--AaB03x--
12 changes: 12 additions & 0 deletions test/spec_multipart.rb
Expand Up @@ -518,6 +518,18 @@ def initialize(*)
params["files"].size.must_equal 252
end

it "parses multiple files with same name" do
env = Rack::MockRequest.env_for("/", multipart_fixture(:multiple_files))
params = Rack::Multipart.parse_multipart(env)
params["files"].must_be_instance_of Array
params["files"][0][:filename].must_equal "file1.txt"
params["files"][0][:tempfile].read.must_equal "foo"
params["files"][1][:filename].must_equal "file2.txt"
params["files"][1][:tempfile].read.must_equal "bar"
params["files"][2][:filename].must_equal "file3.txt"
params["files"][2][:tempfile].read.must_equal "quux"
end

it "parses IE multipart upload and cleans up the filename" do
env = Rack::MockRequest.env_for("/", multipart_fixture(:ie))
params = Rack::Multipart.parse_multipart(env)
Expand Down
2 changes: 1 addition & 1 deletion test/spec_utils.rb
Expand Up @@ -150,7 +150,7 @@ def assert_nested_query(exp, act)
must_equal "foo" => "\"bar\""

Rack::Utils.parse_nested_query("foo=bar&foo=quux").
must_equal "foo" => "quux"
must_equal "foo" => ["bar", "quux"]
Rack::Utils.parse_nested_query("foo&foo=").
must_equal "foo" => ""
Rack::Utils.parse_nested_query("foo=1&bar=2").
Expand Down

0 comments on commit a95077f

Please sign in to comment.