Submit Form And Upload File With Requests
I'm struggling with submitting a particular form with python requests. Other forms on the site I want to use it work fine and I'm able to submit the login form etc. It's just the f
Solution 1:
Use the files
keyword to make your upload, not data
. Don't set the content-type header either; the form is posted as multipart form data, and requests should use the correct content type for that for you:
res = s.post(
url='https://example.com/upload.php',
data={'upload_type': 'standard', 'upload_to': '0'},
files=file)
and put the rest of the form fields in a mapping in data
.
If you want to upload more than one file under the same name, use a sequence of files:
files = {
'userfile[]': [
open('tmp/cover/cover1.jpg', 'rb'),
open('tmp/cover/cover2.jpg', 'rb'),
]
}
res = s.post(
url='https://example.com/upload.php',
data={'upload_type': 'standard', 'upload_to': '0'},
files=files)
Solution 2:
I see two problems with your code:
- You are setting the Content-Type manually. Don't. The library will take care of that. This is esp. because during the multipart form data post, the headers are like:
Content-Type: multipart/form-data; boundary=<blah>
. - According the docs, you should be using a
files
named argument for uploading a file, notdata
.
Use:
res = s.post(url='https://example.com/upload.php',
data=<dict containing form params>,
files=file)
Post a Comment for "Submit Form And Upload File With Requests"