From wechat api doc:

curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requests
url = '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

Answer from kev on Stack Overflow
Top answer
1 of 8
77

From wechat api doc:

curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requests
url = '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

2 of 8
37

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 base64
import json                    

import requests

api = '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 io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = 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()
Discussions

python - Submitting POST Request with Image - Stack Overflow
I'm trying to do my first POST request (on TinEye) that involves uploading an image. I'm trying to piece together bits from these answers: Python POST Request with an Image , How to post image using More on stackoverflow.com
🌐 stackoverflow.com
How upload image with python requests
file = os.getcwd()+'/'+settings.get('IMAGES_STORE')+'/'+settings.get('APMSIZEIMAGE')+'/'+item.get('images')[0]['path'] files = { 'file': open(file, 'rb'), 'ref': file } fileResult = requests.post(self.publish_site+'/ghost/api/'+self.admin_api_key_version+'/admin/images/upload/', files=files, ... More on forum.ghost.org
🌐 forum.ghost.org
0
0
October 29, 2019
Posting image using requests on python - Stack Overflow
See the POST Multiple Multipart-Encoded Files section of the documentation. The library can also handle a username and password pair to handle the Authorization header; simply pass in a (username, password) tuple for the auth keyword argument. Encoding an image to Base64 is not sufficient however. More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
Sending image over POST request with Python Requests - Stack Overflow
I am currently attempting to use Python (3.5) with the Requests library to send a POST request. This POST will send an image file. Here is the sample code: import requests url = "https://api/addr... More on stackoverflow.com
🌐 stackoverflow.com
🌐
ProxiesAPI
proxiesapi.com › articles › uploading-images-with-python-requests
Uploading Images with Python Requests | ProxiesAPI
url = "https://api.example.com/image-upload" headers = {"Authorization": "Client-ID xxx"} r = requests.post(url, headers=headers) ... The first part defines the file name on the server.
🌐
Lightspeedhq
x-series-api.lightspeedhq.com › docs › products_image_uploads_code_sample_python_requests
Image Upload Code Sample - Python with Requests
import requests url = ... headers = { 'authorization': "Bearer {token}" } response = requests.request("POST", url, files=files, headers=headers) ......
Top answer
1 of 1
1

I found an article that showed how to copy the request as a curl from Chrome, import it into Postman, and then export the corresponding python request from Postman, which I have done below as an updated attempt at got the 200 response code. Woohoo!

    def search_image(self, image):
        
        url = "https://tineye.com/result_json/"
        
        cookies = requests.get(url).cookies

        payload={}
        files=[
        ('image',('file', image,'application/octet-stream'))
        ]
        headers = {
        'authority': 'tineye.com',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'en-US,en;q=0.9',
        # 'cookie': '_ga=GA1.2.1487505347.1661754780; sort=score; order=desc; _gid=GA1.2.613122987.1662166051; __cf_bm=VYpWBFxDJVgFr_e6N_51uElQ4P0qmZtysVNuPdG4MU4-1662166051-0-AQ3g7/Ygshplz8dghxLlCTA8TBrR0b+YXr9kOMfagi18Ypry9kWkDQELjUXOGpClZgoX/BjZExzf+3r6aL8ytCau2kM8z5u3sFanPVaA39wOni+AMGy69RFrGBP8om+naQ==; tineye=fz1Bqk4sJOQqVaf4XCHM59qTFw8LSS6aLP3fQQoIYLyVWIsQR_-XpM-E6-L5GXQ8eex1ia7GI0-ffA57yuR-ll0nfPeAPkDzqdp1Uw; _gat_gtag_UA_2430070_8=1',
        'origin': 'https://tineye.com',
        'referer': 'https://tineye.com/search',
        'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
        }

        response = requests.post(url, headers=headers, data=payload, files=files, cookies=cookies, timeout=60)
        return response
🌐
Ghost Forum
forum.ghost.org › developer help
How upload image with python requests - Developer help - Ghost Forum
October 29, 2019 - file = os.getcwd()+'/'+settings.get('IMAGES_STORE')+'/'+settings.get('APMSIZEIMAGE')+'/'+item.get('images')[0]['path'] files = { 'file': open(file, 'rb'), 'ref': file } fileResult = requests.post(self.publish_site+'/ghost/api/'+self.admin_api_key_version+'/admin/images/upload/', files=files, ...
Find elsewhere
🌐
Google Groups
groups.google.com › g › django-users › c › 3ZZEnCxuFGM › m › oXQm3-R1z4sJ
How to use Python Requests Module to upload images to Django Application?
================================== # loop to get messages from console while True: message = input("Enter msg string: ") filename= input("Enter filename (or blank): ") # GET print("--- GET upload_msg") # Create a GET request (but do don't sent it) req = Request('GET', upload_msg_url, data= {}) # Send request forms_dct = get_response(req) # modify forms_dct from GET, and use in next get_response() forms_dct['message_str'] = message # open file for upload fobj = open(filename,'rb') # modify forms_dct from GET, and use in next get_response() forms_dct['photo'] = filename # Create files dictionary
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-upload-files-using-python-requests-library
How to Upload Files Using Python Requests Library - GeeksforGeeks
July 23, 2025 - In this example, below Python code sends a POST request to "https://httpbin.org/post", including both form data ('key': 'value') and a file ('file.txt') uploaded via the `requests` library.
🌐
Python-requests
2.python-requests.org › en › v0.10.5 › user › quickstart
We cannot provide a description for this page right now
🌐
FastAPI
fastapi.tiangolo.com › tutorial › request-files
Request Files - FastAPI
To receive uploaded files, first install python-multipart. Make sure you create a virtual environment, activate it, and then install it, for example: ... This is because uploaded files are sent as "form data".
🌐
Reddit
reddit.com › r/flask › how do i send image with python requests and receive it with flask request ?
r/flask on Reddit: How do I send image with Python requests and receive it with Flask request ?
March 4, 2021 -

Hi Flaskers,

I'm having difficulty receiving image on the Flask backend:

@auth_blueprint.route('/auth/check_image', methods=['POST'])
@cross_origin()
def check_image():
    try:
        image_given = request.files['photo']  # <-- image won't make it to Flask
        img = Image.open(image_given.stream)
        return jsonify({'status': 'OK', 'message': f'{img.width} {img.height}'})

Kivy front-end:

img = {'file': ('photo': open(f'{self.image_path}/example.jpg', 'rb'))}
try:
    response = requests.post('http://www.example.com/auth/check_image', files=img)
    print(str(response.content, 'utf-8'))

Error output:

<title>500 Internal Server Error</title>
03-02 17:06:26.295 15175 15678 I python  : <h1>Internal Server Error</h1>
03-02 17:06:26.295 15175 15678 I python  : <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

Error output from the backend:

"content":"400 Bad Request: The browser (or proxy) sent a request that this server could not understand.","status":"fail"

I've found this block of code that allegedly works:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/im_size", methods=["POST"])
def process_image():
    file = request.files['image']
    # Read the image via file.stream
    img = Image.open(file.stream)

    return jsonify({'msg': 'success', 'size': [img.width, img.height]})


if __name__ == "__main__":
    app.run(debug=True)

url = 'http://127.0.0.1:5000/im_size'
my_img = {'image': open('test.jpg', 'rb')}
r = requests.post(url, files=my_img)

# convert server response into JSON format.
print(r.json())

I found the code here https://jdhao.github.io/2020/04/12/build_webapi_with_flask_s2/, strangely I'm getting status code 400 using it.

Thank you for any insight.

🌐
Stack Abuse
stackabuse.com › how-to-upload-files-with-pythons-requests-library
How to Upload Files with Python's requests Library
September 19, 2021 - In this article, we learned how to upload files in Python using the requests library. Where it's a single file or multiple files, only a few tweaks are needed with the post() method.
🌐
freeCodeCamp
forum.freecodecamp.org › python
POST both image and text - Python - The freeCodeCamp Forum
July 26, 2021 - I’m trying to send a small image and some sensor values from a remote raspberry pi using POST. I can send the sensor values just fine, and I can send the image no problem, but I can’t seem to get it to work when I try to do them both in one POST. url = { 'https://url/post' } files = { 'file': open('test.jpg','rb') } values = { 'datetime': dateTime, 'airqual': airqual, 'temperature': temperature, 'pressure': pressure, 'humidity': humidity } r = requests.post(url=...
🌐
Medium
medium.com › @API4AI › post-a-file-via-http-request-the-ultimate-guide-b23fb70a3f73
POST a File via HTTP Request | The Ultimate Guide | by API4AI | Medium
February 23, 2024 - Here’s how to use it for our ... the Image File: The file is passed as a dictionary to the files parameter, with the key being the name of the form field image and the value being the file itself....