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

如何通过Python Flask实现客户端向服务器传图片?报错求助

问题解决:客户端向Flask服务器传输图片失败的修复

核心问题

你的代码存在两个关键错误导致服务器无法读取图片:

  • 客户端上传的文件键名与服务器期望的不匹配:服务器查找的是"img1",但客户端传递的键是"file"
  • 客户端构建files参数的方式错误,不需要调用read(),直接传递打开的文件对象即可

修正后的代码

server.py(确保键名与客户端一致,原逻辑保留)

if format_type in ['file', 'url']:
    if format_type == 'file':
        try:
            # 键名和客户端保持统一,这里用"img1"对应客户端的上传键
            image = Image.open(io.BytesIO(request.files["img1"].read()))
        except Exception as e:
            # 捕获具体异常方便调试,替换泛型except
            ret = create_respone({}, '3', f'图片读取失败:{str(e)}')
            return ret

client.py(修正键名与files参数格式)

import requests

url = "http://192.168.254.217:5000/predict?format_type=file&get_thumb=false"
# 1. 键名改为和服务器一致的"img1"
# 2. 直接传递打开的文件对象,不要调用read()
files = {'img1': open('image0.jpg', 'rb')}
response = requests.post(url=url, files=files)
print(response.text)

# 更推荐用with语句管理文件,避免资源泄漏:
# with open('image0.jpg', 'rb') as f:
#     files = {'img1': f}
#     response = requests.post(url=url, files=files)
# print(response.text)

额外提示

  • 尽量捕获具体异常(比如PIL.UnidentifiedImageError、KeyError),而非泛型except:,能更精准定位问题
  • 检查服务器端create_respone函数(注意拼写应为response)是否能正确返回标准响应格式

内容的提问来源于stack exchange,提问作者Đinh Dũng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:36:20