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

FastAPI接口UploadFile无法转换为bytearray报错如何解决?

问题原因

FastAPI 中UploadFile是框架封装的异步文件处理对象,本身不存储字节内容,必须调用其异步read()方法才能获取到图片的二进制字节流,你之前直接将UploadFile实例传入转换逻辑,自然会触发类型不匹配的报错。

修复方案

调整两处代码即可:

  1. 先在接口层读取UploadFile的二进制内容,再传入图片处理函数
  2. 简化图片读取逻辑,不需要额外做bytearray转换,直接用读取到的字节构造BytesIO即可

修改后的完整代码如下:
首先是图片读取函数:

from PIL import Image
from io import BytesIO

def read_image(image_bytes):
    pil_image = Image.open(BytesIO(image_bytes))
    # 可选:统一转换为RGB模式,避免PNG等带透明通道的图片后续预测报错
    pil_image = pil_image.convert("RGB")
    return pil_image

然后是接口逻辑:

@app.post('/api/predict')
async def predict_image(file: UploadFile = File(...)):
    # 异步读取图片字节内容
    image_bytes = await file.read()
    img = read_image(image_bytes)
    
    img_array = image.img_to_array(img)
    print(img_array.shape)
    img_array = tf.expand_dims(img_array, 0)  # 创建batch维度

    predictions = model.predict(img_array)
    score = predictions[0]
    # 主动关闭文件句柄
    await file.close()
    return score
额外注意事项
  • 增加convert("RGB")逻辑可避免PNG、GIF等带非RGB通道的图片触发后续张量转换报错
  • 如果存在大文件上传场景,可改为分片读取,普通图像预测场景全量读取性能足够
  • 如需限制上传文件类型,可提前判断file.filename的后缀或者读取图片后校验pil_image.format字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:45:02