You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用本地Python Flask OCR接口连接被拒,如何排查解决?

Flutter调用Flask OCR接口遇连接拒绝+文本提取失败的解决方案

一、连接被拒绝的核心修复

连接拒绝的本质是Flutter客户端无法访问到本地Flask服务,从两个关键环节调整:

  1. 修改Flask服务的监听范围
    默认app.run()仅允许本地(127.0.0.1)访问,需改成允许局域网内所有设备访问:
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
  • host='0.0.0.0':开放服务至局域网
  • port=5000:保持端口与Flutter请求一致,可自定义
  1. 修正Flutter的请求地址
    根据运行环境替换目标地址:
  • Android模拟器:将http://127.0.0.1:5000改为http://10.0.2.2:5000(模拟器内置映射,指向电脑本地IP)
  • 真机:改为电脑的局域网IP(通过ipconfig/ifconfig查看,例如http://192.168.1.100:5000)

二、Python代码的字段匹配错误

Flutter上传的文件字段为image,但后端错误取了_imagefile,导致无法读取文件,直接修改后端代码:

@app.route('/extract_text', methods=['POST'])
def extract_text():
    if 'image' not in request.files:
        return jsonify({'error': 'No image file found'})

    # 修正字段名,与前端保持一致
    image_file = request.files['image']
    image = Image.open(image_file)

    text = pytesseract.image_to_string(image, lang='eng')
    return jsonify({'text': text})

三、其他潜在问题排查

  1. Tesseract路径配置(Windows用户)
    Windows系统需手动指定Tesseract安装路径,否则会触发识别失败:
import pytesseract
# 替换为你的Tesseract实际安装路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
  1. Flutter网络权限配置
  • Android:在android/app/src/main/AndroidManifest.xml中添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
  • iOS:在ios/Runner/Info.plist中添加HTTP请求许可(测试阶段用,正式环境建议切换HTTPS):
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

修复后的完整代码示例

Flutter端修正后的请求逻辑

Future<void> _extractTextFromImage() async {
  try {
    // 替换为对应环境的正确地址
    var request = http.MultipartRequest(
      'POST',
      Uri.parse('http://10.0.2.2:5000/extract_text'),
    );
    request.files
        .add(await http.MultipartFile.fromPath('image', _imageFile!.path));

    var response = await request.send();
    var responseData = await response.stream.bytesToString();
    var decodedResponse = jsonDecode(responseData);

    setState(() {
      _extractedText = decodedResponse['text'];
    });
  } catch (e) {
    debugPrint('Error extracting text: $e');
  }
}

Python端修正后的完整代码

from flask import Flask, request, jsonify
import pytesseract
from PIL import Image

# Windows用户需添加此行配置Tesseract路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

app = Flask(__name__)

@app.route('/extract_text', methods=['POST'])
def extract_text():
    if 'image' not in request.files:
        return jsonify({'error': 'No image file found'})

    image_file = request.files['image']
    image = Image.open(image_file)

    text = pytesseract.image_to_string(image, lang='eng')
    return jsonify({'text': text})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

内容的提问来源于stack exchange,提问作者a HAMZAY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:45:08