I am using the Python requests module to send a multi-part HTTP POST request that contains both form-data and a file attachment.
The "Content-disposition" header for each multi-part object is set to "form-data", including the file part.
I need the "Content-disposition" header for the form-data parts to still say "form-data", but the "Content-disposition" header for the file part must say "attachment" and not "form-data".
How do I change the content-disposition header for the file-part only?
My code:
#Python 3.7.3 (default, Apr 24 2019, 13:20:13) [MSC v.1915 32 bit (Intel)]
import requests
#USER PARAMETERS
user_name = 'user_account'
password = 'user_password'
token = '45Hf4xGhj'
#REQUESTS PARAMETERS
url = '192.168.0.2'
headers = {'content-type': 'multi-part/form-data'}
data = {'Username':user_name, 'Password':password, 'Token':token}
files = {'settings': ('settings.xml', open('settings.xml', 'rb'), 'app/xml')}
#POST
response = requests.post(url, headers=headers, data=data, files=files)
This is what the file-part's header looks like with Python requests:
Content-Type: app/xml
Content-Disposition: form-data; name="settings"; filename="settings.xml"
and this is what I need the header of the file-part to look like:
Content-Type: app/xml
Content-Disposition: attachment; name="settings"; filename="settings.xml"
I also tried to change the header by adding a header parameter to the file:
files = {'settings': ('settings.xml', open('settings.xml', 'rb'),
'app/xml', {'Content-Disposition':'attachment'})}
but that had no effect. I can specify any other custom header and it will add it, but it does not change the "Content-Disposition" header if I use the approach.
Any ideas?
Using the toolbelt:
m = MultipartEncoder( fields={'Username': user_name,
'Password': password,
'Token': token,
'settings': ('settings', open('settings.xml', 'rb'),
'app/xml',
{'Content-Disposition':'attachment'}
)
}
)
r = requests.post('http://httpbin.org/post',
data=m,
headers={'Content-Type': m.content_type})
results in
...--2ba9624051854b6d961bad262a1792fc Content-Disposition: form-data; name="settings"; filename="settings" Content-Type: app/xml <?xml version="1.0" encoding="utf-16"?>...