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

React Native图片上传至服务器无报错但未成功问题排查

React Native图片上传无报错但失败的排查与解决

下面针对你的代码逐一排查问题并给出修复方案:

1. 移除手动设置的Content-Type头

手动指定multipart/form-data会丢失自动生成的boundary分隔符,导致服务器无法正确解析表单数据。fetch会自动根据FormData生成包含boundary的正确Content-Type,直接删除这个headers配置即可:

let res = await fetch('https://url', {
    method: 'post',
    body: data,
    // 移除以下手动设置的Content-Type
    // headers: {
    //   'Content-Type': 'multipart/form-data; ',
    // },
});

2. 确保FormData中的文件格式合规

React Native中,图片对象需要明确包含uri、type、name三个属性才能被FormData正确识别。如果你的selectedImage1仅返回uri,需要包装成标准格式:

const fileToUpload = selectedImage1;
data.append('file_attachment', {
  uri: Platform.OS === 'android' ? fileToUpload.uri : fileToUpload.uri.replace('file://', ''),
  type: fileToUpload.type || 'image/jpeg', // 根据实际图片类型调整
  name: fileToUpload.fileName || `upload_${Date.now()}.jpg` // 确保文件名存在
});

注意:iOS的uri需要去掉file://前缀,Android可直接使用原uri。

3. 完善错误处理逻辑

当前代码未处理网络异常、服务器错误等情况,即使上传失败也可能无法捕获错误信息。添加try/catch并检查响应状态:

let uploadImage = async () => {
  if (!selectedImage1) {
    alert('请选择图片');
    return;
  }
  try {
    const data = new FormData();
    data.append('name', 'Image Upload');
    data.append('file_attachment', {
      uri: Platform.OS === 'android' ? selectedImage1.uri : selectedImage1.uri.replace('file://', ''),
      type: selectedImage1.type || 'image/jpeg',
      name: selectedImage1.fileName || `upload_${Date.now()}.jpg`
    });
    let res = await fetch('https://url', {
        method: 'post',
        body: data,
    });
    if (!res.ok) {
      throw new Error(`服务器返回错误:${res.status}`);
    }
    let responseJson = await res.json();
    console.log(responseJson);
  } catch (error) {
    console.error('上传失败:', error);
    alert('上传失败,请检查网络或重试');
  }
};

4. 验证服务器端配置

  • 确认服务器接收的字段名是file_attachment,与你FormData中append的key完全一致
  • 检查服务器目标文件夹是否存在且具备写入权限
  • 查看服务器日志,确认是否接收到请求但解析失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:43:20