React Native中Axios+FormData上传图片至后端失败排查求助
React Native Axios 上传图片表单数据异常排查方案
在React Native中使用Axios向后端提交包含图片的表单数据,已将图片数据封装为带有uri、name等属性的对象,但请求后返回的图片路径和URL为null,其余数据上传正常。无后端权限,但Postman可正常上传图片,以下是排查方案:
const data = new FormData(); // const fileUri = Platform.OS === 'ios' ? image.replace('file://', '') : image; const fileExtension = getFileExtension(image) || 'jpg'; // Default extension 'jpg' const fileName = `imageMed.${fileExtension}`; data.append('file', { uri: image, name: fileName, type: `image/${fileExtension}`, }); data.append('name', MedicineName); data.append('dosage', dose); data.append('start_time', `${Newdate} ${Newtime}`); data.append('number_of_days', days); data.append('frequency', freNumber); data.append('days_of_the_week', '1,2,3'); data.append('st_notification', !isNotify ? 0 : 1); data.append('st_critical', !priority ? 0 : 1); data.append('default_icon', selectedImage); data.append('medicine_schedules', 'test_string'); let config = { method: 'post', maxBodyLength: Infinity, url: 'https://api-patient-dev.easy-health.app/medicines', headers: { 'Content-Type': 'multipart/form-data', 'Authorization': `Bearer ${access_token}`, }, data: data }; console.log(data); axios.request(config) .then((response) => { console.log(JSON.stringify(response.data)); renderAlarmComponents(response.data, userId); }) .catch((error) => { console.log(error); }) .finally(() => { setShowLoader(false); // navigation.navigate('Dashboard', { // isChanged: true, // }); });
排查步骤
- 恢复iOS URI处理逻辑:iOS平台下,文件URI需要去掉
file://前缀才能被FormData正确解析。取消注释const fileUri = Platform.OS === 'ios' ? image.replace('file://', '') : image;,并将data.append('file', {...})中的uri: image改为uri: fileUri。 - 移除手动设置的Content-Type:Axios会自动根据FormData生成包含boundary的
multipart/form-data请求头,手动设置反而会导致后端无法正确解析表单。删除headers中的'Content-Type': 'multipart/form-data'。 - 验证图片URI有效性:确认
image变量的URI格式符合平台要求:Android通常是content://或file://开头,iOS是正确的本地文件路径。通过console.log(image)检查URI是否正确。 - 校验文件类型与扩展名一致性:确保
getFileExtension函数能正确提取图片扩展名,比如图片为PNG时,type需设为image/png,避免扩展名与MIME类型不匹配的情况。可直接打印fileExtension的值验证。 - 对齐Postman请求结构:在Postman中查看成功请求的FormData详情(字段名、文件名、Content-Type等),对比代码中FormData的字段是否完全一致,比如文件字段名是否为
file,文件名格式是否匹配。 - 升级Axios版本:部分旧版本Axios在React Native环境下处理FormData存在兼容性问题,尝试将Axios升级至最新稳定版。
- 调试FormData内容:发送请求前用
console.log([...data.entries()])打印FormData的所有条目,确认文件对象的uri、name、type属性均正确设置。
内容的提问来源于stack exchange,提问作者syedmisbah ali
相关产品推荐
相关产品推荐

