Upload Image using POST form data in Python-requests Upload Image using POST form data in Python-requests python python

Upload Image using POST form data in Python-requests


From wechat api doc:

curl -F media=@test.jpg "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requestsurl = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'files = {'media': open('test.jpg', 'rb')}requests.post(url, files=files)

Doc: https://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file


In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py

import base64import json                    import requestsapi = 'http://localhost:8080/test'image_file = 'sample_image.png'with open(image_file, "rb") as f:    im_bytes = f.read()        im_b64 = base64.b64encode(im_bytes).decode("utf8")headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}  payload = json.dumps({"image": im_b64, "other_key": "value"})response = requests.post(api, data=payload, headers=headers)try:    data = response.json()         print(data)                except requests.exceptions.RequestException:    print(response.text)

server.py

import ioimport json                    import base64                  import logging             import numpy as npfrom PIL import Imagefrom flask import Flask, request, jsonify, abortapp = Flask(__name__)          app.logger.setLevel(logging.DEBUG)    @app.route("/test", methods=['POST'])def test_method():             # print(request.json)          if not request.json or 'image' not in request.json:         abort(400)                 # get the base64 encoded string    im_b64 = request.json['image']    # convert it into bytes      img_bytes = base64.b64decode(im_b64.encode('utf-8'))    # convert bytes data to PIL Image object    img = Image.open(io.BytesIO(img_bytes))    # PIL image object to numpy array    img_arr = np.asarray(img)          print('img shape', img_arr.shape)    # process your img_arr here            # access other keys of json    # print(request.json['other_key'])    result_dict = {'output': 'output_key'}    return result_dict    def run_server_api():    app.run(host='0.0.0.0', port=8080)    if __name__ == "__main__":         run_server_api()


I confronted similar issue when I wanted to post image file to a rest API from Python (Not wechat API though). The solution for me was to use 'data' parameter to post the file in binary data instead of 'files'. Requests API reference

data = open('your_image.png','rb').read()r = requests.post(your_url,data=data)

Hope this works for your case.