Skip to content

How to pass array to form data (multipart/form-data) #903

@lukasz-madon

Description

@lukasz-madon

I need to call API using multipart/form-data with list of strings and list of objects

data = aiohttp.FormData()
data.add_field("emails", candidate["email"], content_type="multipart/form-data")
data.add_field("phones[]", [{"value": phone}], content_type="multipart/form-data")

If I'm not mistaken FormData is designed to support urlencoded params or bytes for files only. Passing anything other than bytes results in ClientRequestError: Can not write request body. Is there a better way that passing everything as files?

What is more the

data.add_field("emails[]", bytes(candidate["email"], "ascii"), content_type="multipart/form-data")

results in emails%5B%5D and form data doesn't allow bytes as names

        elif isinstance(value, (bytes, bytearray, memoryview)):
            if filename is None and content_transfer_encoding is None:
                filename = name

        type_options = multidict.MultiDict({'name': name})
        if filename is not None and not isinstance(filename, str):
            raise TypeError('filename must be an instance of str. '
                            'Got: %s' % filename)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions