Search code examples
pythonflaskpostserverclient

How to send image from client to server by flask python


I've tried to send an image from client to server like enter image description here. But server can not read image and return Exept.
Plese help me. Thank you very much.

server.py

if format_type in ['file', 'url']:
        if format_type == 'file':
            try:
                image = Image.open(io.BytesIO(request.files["img1"].read()))
            except:
                ret = create_respone({}, '3', 'Incorrect image format')
                return ret
client.py

import requests
url = "http://192.168.254.217:5000/predict?format_type=file&get_thumb=false"
file = {'file': open('image0.jpg', 'rb').read()}
response = requests.post(url = url, files=file)
print(response.text)

The result is Except. How can i send a image from client to server. Thank you.


Solution

  • Almost there, help yourselves with the changes below:

    Currently not able to infer format_type variable. but guessing from the request format below should work.

    server.py

    @app.route('/predict', methods=['POST'])
    def predict():
        format_type = request.args.get('format_type', default=None)
    
        if format_type in ['file', 'url']:
            if format_type == 'file':
                try:
                    image = Image.open(io.BytesIO(request.files["img1"].read()))
                    return jsonify({'message': 'Success!'})
                except:
                    ret = create_respone({}, '3', 'Incorrect image format')
                    return ret
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)
    

    client.py

    import requests
    
    url = "http://127.0.0.1:5000/predict?format_type=file&get_thumb=false"
    file = {'img1': open('image0.jpg', 'rb')}
    response = requests.post(url=url, files=file)
    print(response.text)
    

    The only change I did was I bound the port to 127.0.0.1, you need to change it according to your need.

    Hope this helps.