0

I am relatively new to python and enjoying every day I program in it. I have been looking around for a possible solution to figure out how to post an image in a multipart-form, binary format, with a form tag. The API I am trying to call is expecting a binary image in a form. The request payload sample I have is:

----WebkitFormBoundaryM817iTBsSwXz0iv8
Content-Disposition: form-data, name="image"; filename="123BMW.jpg"
Content-Type: image/jpeg
----WebkitFormBoundaryM817iTBsXwxz0iv8

I have tried several ideas based on some basic requests examples. Any ideas, thoughts or pointers on where to start looking for such a solution?

def Post_Image(urlPath, filePath, fileName): 
    url = urlPath headers = {'content-type': 'multipart/form-data'} 
    files = {'file':(fileName, open(filePath,'rb'))} 
    payload = {"Content-Disposition": "form-data", "name":fileName} 
    payload = urllib.urlencode(payload) 
    resp = requests.post(url, data=payload, headers=headers, files= files)
Todor Minakov
  • 19,097
  • 3
  • 55
  • 60

1 Answers1

0

The problem is you're setting both the data and files parameters, this part of the code sample here:

payload = urllib.urlencode(payload) 
resp = requests.post(url, data=payload, headers=headers, files= files)

If both are present, and data value is a string, only it will be in the request. Drop it, and the files will be present.

Todor Minakov
  • 19,097
  • 3
  • 55
  • 60