React Native向FastAPI后端传图片遇422错误,求正确实现方案
React Native上传图片到FastAPI的正确方式
你遇到的422错误是因为FormData格式不符合FastAPI的解析要求,直接传入ImagePicker返回的assets[0]对象无法被正确识别。以下是修正方案:
1. 正确构造FormData对象
不能直接将image.assets[0]传给formData.append,需要手动指定文件的uri、type和name三个核心属性:
var formData = new FormData(); formData.append('image', { uri: image.assets[0].uri, type: image.assets[0].type, name: image.assets[0].fileName || 'default_image.jpg' // 必须提供文件名,FastAPI依赖此字段解析 });
2. 避免手动设置Content-Type请求头
无论使用fetch还是axios,都不要手动添加Content-Type: multipart/form-data。React Native会自动根据FormData生成包含正确boundary的请求头,手动设置会导致FastAPI无法解析文件:
使用fetch的示例
fetch('http://你的FastAPI接口地址/', { method: 'POST', body: formData }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
使用axios的示例
import axios from 'axios'; axios.post('http://你的FastAPI接口地址/', formData) .then(res => console.log(res.data)) .catch(err => console.error(err));
额外检查点
- 确认
image.assets[0].uri是有效的文件路径(Android为file://开头,iOS路径格式React Native会自动兼容) - FormData中append的key(这里是
image)必须和FastAPI接口定义的参数名完全一致 - 确保设备能访问到FastAPI服务(同一局域网内注意防火墙/端口开放,公网服务需确认地址正确)
内容的提问来源于stack exchange,提问作者akilesh raj
相关产品推荐
相关产品推荐

