前端上传图片,Python后端接收

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload</title>
</head>
<body>
    <h1>Image Upload</h1>
    <input type="file" id="imageInput">
    <button onclick="uploadImage()">Upload</button>
    <script>
        function uploadImage() {
            const imageInput = document.getElementById('imageInput');
            const file = imageInput.files[0];

            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const imageBase64 = event.target.result;
                    const data = {
                        image: imageBase64,
                        direction: 0
                    };

                    fetch('http://127.0.0.0:5000/slot_count', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    })
                    .then(response => response.json())
                    .then(result => {
                        console.log(result);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
                };
                reader.readAsDataURL(file);
            }
        }
    </script>
</body>
</html>

Python后端代码

import base64
from gevent import pywsgi
from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import cv2
import traceback

app = Flask(__name__)
CORS(app, resources=r'/*')  # 跨域
app.config['JSON_AS_ASCII'] = False  # 返回显示中文


@app.route('/', methods=['GET'])
def verify_connect():
    return jsonify({'code': 200, 'msg': 'success', 'data': ["connection successful"]})


@app.route('/slot_count', methods=['POST'])
def predict():
    ret = []

    try:
        data = request.json
        direction = data['direction']
        print(direction)

        base64_image = data['image']
        image_data = base64.b64decode(base64_image.split(',')[-1])
        image = cv2.imdecode(np.frombuffer(image_data, np.uint8), cv2.IMREAD_COLOR)
        print(image.shape)

        cv2.imshow('img', image)
        cv2.waitKey()

        code = 200
        msg = "success"

    except ValueError as ve:
        traceback.print_exc()
        code = 400
        msg = str(ve)

    except Exception as e:
        traceback.print_exc()
        code = 500
        msg = str(e)

    result = {'code': code, 'msg': msg, 'data': ret}

    return jsonify(result)


if __name__ == '__main__':
    app.run('0.0.0.0', 5000, debug=True)
    # server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
    # server.serve_forever()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值