質問

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
役に立ちましたか?

解決

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--
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top