Python requests, how to add content-type to multipart/form-data request
<p>I Use python requests to upload a file with PUT method.</p>

<p>The remote API Accept any request only if the body contains an attribute 
Content-Type:i mage/png not as Request Header </p>

<p>When i use python requests , the request rejected because missing attribute</p>

<p><a href="http://i.stack.imgur.com/8KQ0F.png" rel="nofollow"><img src="http://i.stack.imgur.com/8KQ0F.png" alt="This request is rejected on this image"></a></p>

<p>I tried to use a proxy and after adding the missing attribute , it was accepted</p>

<p>See the highlighted text</p>

<p><a href="http://i.stack.imgur.com/zzFBn.png" rel="nofollow"><img src="http://i.stack.imgur.com/zzFBn.png" alt="Valid request"></a> </p>

<p>but i can not programmatically add it , How can i do it?</p>

<p>And this is my code:</p>

<pre><code>files = {'location[logo]': open(fileinput,'rb')} 

ses = requests.session()
res = ses.put(url=u,files=files,headers=myheaders,proxies=proxdic)
</code></pre>

<p>As per the [docs][1, you need to add two more arguments to the tuple, filename and the content type:</p>

<pre><code>#         filed name         filename    file object      content=type
files = {'location[logo]': ("name.png", open(fileinput),'image/png')}
</code></pre>

<p>You can see a sample an example  below:</p>

<pre><code>In [1]: import requests

In [2]: files = {'location[logo]': ("foo.png", open("/home/foo.png"),'image/png')}

In [3]: 

In [3]: ses = requests.session()

In [4]: res = ses.put("http://httpbin.org/put",files=files)

In [5]: print(res.request.body[:200])
--0b8309abf91e45cb8df49e15208b8bbc
Content-Disposition: form-data; name="location[logo]"; filename="foo.png"
Content-Type: image/png

ï¿½PNG

IHDRï¿½ï¿½:dï¿½tEXtSoftw
</code></pre>

<p>For future reference, <a href="https://github.com/kennethreitz/requests/issues/1495" rel="nofollow">this comment</a> in a old related issue explains all variations:</p>

<pre><code># 1-tuple (not a tuple at all)
{fieldname: file_object}

# 2-tuple
{fieldname: (filename, file_object)}

# 3-tuple
{fieldname: (filename, file_object, content_type)}

# 4-tuple
{fieldname: (filename, file_object, content_type, headers)}
</code></pre>

python file http upload python-requests