How to upload a file in a urllib2 request

1.1k Views Asked by At

I'm trying to use the kairos facial recognition API, and I need to upload a local file. The api documentation says that the image parameter needs to be a "Publicly accessible URL or Base64 encoded photo." In the example code, they use the data parameter for urllib2.request, and to this they pass the values string which I think is json. My question is, how can I give them a local file instead of the url "http://media.kairos.com/kairos-elizabeth.jpg"?

1

There are 1 best solutions below

0
Thiagarajan On

You can read the local image and do a base64 encoding. You can then pass it as "image" key-value pair in "values" that you form.

Below is a sample code. It does not use urllib2. But its not too different.

with open ('messi.jpg','rb') as imgFh:
    img = imgFh.read()

values = {"image": b64encode(img),
    "subject_id": "Messig",
    "gallery_name": "faces"}

You can pass this "values" as "data" in you request. It should work.