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

使用react-native-image-crop-picker上传大文件出现网络错误如何解决

解决方案

1. 移除手动配置的Content-Type请求头

使用FormData上传时,React Native原生网络层会自动生成携带boundary参数的multipart/form-data请求头,手动配置该头会覆盖自动生成的boundary标识,导致大文件上传时服务端无法正确拆分解析请求体,小文件因为体积小、解析容错性高反而可以正常运行。

2. 延长请求超时时间

大文件上传耗时更长,axios默认超时时间通常为10秒,超出后会直接中断请求抛出Network Error。

3. 禁用axios默认的请求体转换逻辑

axios默认会尝试转换所有请求体数据,对FormData对象的额外处理在大文件场景下会导致数据异常。

4. 原生端配置适配

  • 安卓端:在android/app/src/main/AndroidManifest.xml的application节点添加android:largeHeap="true",提升应用内存上限,避免大文件读取时内存溢出。如果后端接口为HTTP协议,还需要添加网络安全配置允许明文流量请求。
  • iOS端:在项目info.plist中配置NSAllowsArbitraryLoads为true,解除ATS系统对非HTTPS请求的限制。

修改后的完整代码

import ImagePicker from 'react-native-image-crop-picker';
import axios from "axios";
import { Platform, TouchableOpacity, Text } from 'react-native';

function uploadFile(){
  ImagePicker.openCamera({
    mediaType: 'any',
  }).then(file=> {
    const body = new FormData();
    body.append('vurl', {
      name: file.fileName,
      type: file.mime,
      uri: Platform.OS === 'ios' ? file.path.replace('file://', '') : file.path,
    });

    axios({
      method:"post",
      url:"替换为你的服务端接口地址",
      data:body,
      headers: {
        Accept: 'application/json',
      },
      timeout: 300000, // 设置5分钟超时,可根据实际业务调整
      transformRequest: [data => data] // 禁用默认请求体转换逻辑
    })
      .then((res) => {
        console.log(JSON.stringify(res));
      })
      .catch((err) => {
        console.log('上传错误', err);
        console.log('服务端返回错误', err.response);
      });
  }).catch(err => {
    console.log('选择文件错误', err);
  });
}

// 调用处代码
<TouchableOpacity onPress={uploadFile}>
    <Text>upload file</Text>
</TouchableOpacity>

如果上述配置仍然无法解决问题,可以替换为原生实现的上传库,大文件场景下兼容性更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:15:03