Flutter使用Dio上传图片至FastAPI报422错误求助
问题分析与解决方案
核心问题
返回422状态码的原因是请求格式错误:你当前通过queryParameters传递File对象,这不符合文件上传的规范。FastAPI接收图片需要的是multipart/form-data格式的表单上传,而queryParameters仅用于传递URL查询参数(如?key=value),无法正确传输文件内容。Postman测试正常是因为它默认使用了正确的表单上传方式。
修正步骤
1. 修改Dio封装代码
更新DioHelper的postImage方法,改用FormData构造文件上传请求:
import 'package:dio/dio.dart'; class DioHelper{ static Dio? dio; static init(){ dio=Dio( BaseOptions( baseUrl: 'http://192.168.1.5:8000/', receiveDataWhenStatusError: true ) ); } static Future<Response> postImage({ required String url, required File imageFile, }) async { // 构造multipart/form-data格式的表单数据 FormData formData = FormData.fromMap({ 'image': await MultipartFile.fromFile( imageFile.path, // 保留文件名后缀,帮助FastAPI识别图片格式 filename: imageFile.path.split('/').last, ), }); return await dio!.post(url, data: formData); } }
2. 调整图片上传调用代码
在ImagePickerPage中修改按钮点击事件的调用逻辑:
MaterialButton( onPressed: () { if (imageFile != null) { DioHelper.postImage(url: 'predict', imageFile: imageFile!) .then((value) { print(value.data['class']); }) .catchError((error) { print(error.toString()); }); } else { print('No image selected'); } }, child: const Text('press'), )
3. 确认FastAPI接口定义(后端侧)
确保你的FastAPI接口是通过UploadFile接收文件的,示例如下:
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/predict") async def predict(image: UploadFile = File(...)): # 此处编写图片处理与模型预测逻辑 return {"class": "你的预测结果"}
额外注意事项
- 确保在Flutter项目的
main函数中初始化了DioHelper:DioHelper.init(); - 检查图片文件路径是否正确,文件名需包含
.png或.jpg后缀 - 若仍有问题,可以给Dio添加拦截器打印完整请求信息,方便调试:
dio!.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
内容的提问来源于stack exchange,提问作者assem el hadidi
相关产品推荐
相关产品推荐

