http icon indicating copy to clipboard operation
http copied to clipboard

Multipart form request with fields of the same name only retains one field value

Open AfzalivE opened this issue 6 years ago • 6 comments

With Multipart form data, it is allowed to have multiple fields of the same name with different values and they all are submitted to the server.

A curl example of that is below (from Mailgun API documentation):

curl -s --user 'api:YOUR_API_KEY' \
   https://api.mailgun.net/v3/routes \
   -F priority=0 \
   -F description='Sample route' \
   -F expression='match_recipient(".*@YOUR_DOMAIN_NAME")' \
   -F action='forward("http://myhost.com/messages/")' \
   -F action='stop()'

Here is the test case:

  test('with multiple fields of the same name', () {
    var request = http.MultipartRequest('POST', dummyUrl);
    request.fields['field1'] = 'value1';
    request.fields['field1'] = 'value2';

    expect(request, bodyMatches('''
        --{{boundary}}
        content-disposition: form-data; name="field1"

        value1
        --{{boundary}}
        content-disposition: form-data; name="field1"

        value2
        --{{boundary}}--
        '''));
  });

The above test case fails because we store fields in a Map and so value2 replaces the previously set value1 for field1.

AfzalivE avatar May 15 '19 16:05 AfzalivE

Closing as a duplicate of #24

natebosch avatar May 28 '19 19:05 natebosch

@natebosch that one is for headers. This one is for fields. Would be nice to get some feedback on the PR.

AfzalivE avatar May 28 '19 20:05 AfzalivE

Does it work to do something like:

    var request = http.MultipartRequest('POST', dummyUrl);
    request.fields['field1[0]'] = 'value1';
    request.fields['field1[1]'] = 'value2';

natebosch avatar May 28 '19 21:05 natebosch

Any alternative solution? It seems for iOS - AlamoFire and Android - Retrofit is able to submit multiple files with same field key.

josephchenghmlet avatar Aug 19 '19 04:08 josephchenghmlet

I know that this is an old issue, but @natebosch suggestion will not work for all cases if the server implementation doesn't handle the bracket notation as they will be treated as different keys.

And even for those server implementations that support the above, it still will be limited because you'll have to always provide an array index.

In my opinion tagging the http package with v1.0.0 wasn't well thought out, because currently unless the MultipartRequest.fields type change I'm not sure if this can be fixed (the same apply for the linked headers issue).

ganigeorgiev avatar Jun 21 '23 13:06 ganigeorgiev