pythonhttppostpython-requests

python set-up boundary for POST using multipart/form-data with requests


I want to send a file using requests but the server works with a fixed boundary set at *****. I'm only able to send a file but the requests module creates a random boundary. How do I overwrite it?

import requests

url='http://xxx.xxx.com/uploadfile.php'
fichier= {'uploadedfile':open('1103290736_2016_03_23_13_32_55.zip','rb')}
headers2={'Connection':'Keep-Alive','User-Agent':'Dalvik/1.6.0 (Linux; U; Android 4.4.2; S503+ Build/KOT49H)','Accept-Encoding':'gzip'}
session= requests.Session()
session.post(url,headers=headers2,files=fichier)
session.close()

Solution

  • Boy, that's one very broken server. If you can, fix the server instead.

    You can't tell requests what boundary to pick. You can instead build your own multipart/form-data payload, using the email.mime package:

    from email.mime.multipart import MIMEMultipart
    from email.mime.application import MIMEApplication
    
    related = MIMEMultipart('form-data', '*****')  # second argument is the boundary.
    file_part = MIMEApplication(
        open('1103290736_2016_03_23_13_32_55.zip', 'rb').read(),
        # optional: set a subtype: 'zip',
    )
    file_part.add_header('Content-disposition', 'form-data; name="uploadedfile"')
    related.attach(file_part)
    
    body = related.as_string().split('\n\n', 1)[1]
    headers = dict(related.items())
    headers['User-Agent'] = 'Dalvik/1.6.0 (Linux; U; Android 4.4.2; S503+ Build/KOT49H)'
    
    r = session.post(url, data=body, headers=headers)
    

    This sets Content-Type: multipart/form-data; boundary="*****" as the header, and the body uses ***** as the boundary (with appropriate -- pre- and postfixes).