How to arrange the order of data and file using requests to post multipart/form-data?

痞子三分冷 提交于 2019-12-21 21:42:21

问题


I want to arrange file in front of data. If I try the traditional way, the data appears in front of file. To be more specifically, I want myfile to appear before form_value.

form_value={'exp':'python', 'ptext':'text', 'board':'Pictures'}
myfile = {'up': ('aa.png', open('aa.png', 'rb'), 'image/png')}
r = requests.post(url, files=myfile, data=form_value, cookies=cookie)

result

Content-Type: multipart/form-data; boundary=170e4a5db6d74d5fbb384dfd8f2d33ce

--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="ptext"

text
--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="board"

Pictures
--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="exp"

python
--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="up"; filename="aa.png"
Content-Type: image/png

回答1:


requests always places files after data, but you can add your data parameters to the files argument instead.

You then do have to use a list with key-value tuples, instead of a dictionary, to preserve order. And you need to provide the filename and content type entries as None to make sure that requests doesn't try and give you the wrong headers:

files = [
    ('up', ('aa.png', open('aa.png', 'rb'), 'image/png')),
    ('exp', (None, 'python', None)),
    ('ptext', (None, 'text', None)),
    ('board', (None, 'Pictures', None)),
]

r = requests.post(url, files=files, cookies=cookie)

This produces:

Content-Type: multipart/form-data; boundary=6f9d948e26f140a289a9e8297c332a91

--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="up"; filename="aa.png"
Content-Type: image/png

[ .. image data .. ]

--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="exp"

python
--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="ptext"

text
--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="board"

Pictures
--0ca5f18576514b069c33bc436ce6e2cd--


来源:https://stackoverflow.com/questions/21091802/how-to-arrange-the-order-of-data-and-file-using-requests-to-post-multipart-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!