With requests
, when using POST with simple data, I can use the same name for multiple values. The CURL command:
curl --data "source=contents1&source=contents2" example.com
can be translated to:
data = {'source': ['contents1', 'contents2']}
requests.post('example.com', data)
The same doesn't work with files. If I translate the working CURL command:
curl --form "source=@./file1.txt" --form "source=@./file2.txt" example.com
to:
with open('file1.txt') as f1, open('file2.txt') as f2:
files = {'source': [f1, f2]}
requests.post('example.com', files=files)
only the last file is received.
MultiDict
from werkzeug.datastructures
doesn't help either.
How to submit multiple files with the same POST name?
Don't use a dictionary, use a list of tuples; each tuple a (name, file)
pair:
files = [('source', f1), ('source', f2)]
The file
element can be another tuple with more detail about the file; to include a filename and the mimetype, you can do:
files = [
('source', ('f1.ext', f1, 'application/x-example-mimetype'),
('source', ('f2.ext', f2, 'application/x-example-mimetype'),
]
This is documented in the POST Multiple Multipart-Encoded Files section of the Advanced Usage chapter of the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With