Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit multiple files with the same POST name with requests?

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?

like image 742
Arseni Mourzenko Avatar asked Dec 14 '22 19:12

Arseni Mourzenko


1 Answers

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.

like image 58
Martijn Pieters Avatar answered Jan 04 '23 04:01

Martijn Pieters