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

如何将react-native-image-crop-picker返回的图片在React Native中上传?

React Native 图片上传适配方案

问题原因

Web端React上传时传入的是浏览器标准File类型的originFileObj对象,React Native中不存在浏览器的FileAPI,FormData处理本地文件的语法为RN自定义实现,和Web端不一致,所以直接传返回对象会触发后端multer的文件校验错误。

具体实现代码

import ImageCropPicker from 'react-native-image-crop-picker';
import axios from 'axios';
// 如果你RN项目中用AsyncStorage存储token,需要导入替换localStorage
// import AsyncStorage from '@react-native-async-storage/async-storage';

const onSubmit = async () => {
  // 图片选择裁剪逻辑,可根据你的业务调整参数
  const croppedImage = await ImageCropPicker.openPicker({
    width: 400,
    height: 400,
    cropping: true,
    mediaType: 'photo'
  });

  const form = new FormData();
  // 按照RN要求的格式构造文件字段
  form.append('file', {
    uri: croppedImage.path,
    name: `img_${Date.now()}.${croppedImage.mime.split('/')[1]}`,
    type: croppedImage.mime
  });

  axios.post("你的上传接口地址", form, {
    headers: {
      Authorization: `bearer ${localStorage.getItem("token")}`,
      // 手动指定multipart类型,避免RN下axios无法自动识别
      "Content-Type": "multipart/form-data"
    },
  })
  .then(res => console.log('上传成功', res))
  .catch(err => console.log('上传失败', err.response?.data || err.message))
};

兼容注意事项

  • iOS端如果出现上传失败,可以尝试将croppedImage.path开头的file://前缀删除后再赋值给uri
  • Android端需要在AndroidManifest.xml中配置网络权限、文件读写权限,iOS端需要配置相册访问权限
  • 你现有后端的multer配置无需修改,只要上传的mime类型和你配置的映射表匹配即可正常解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:15:08