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

React Native中Expo ImagePicker上传图片至自建服务器失败求助

问题解决:Expo ImagePicker 图片上传自建服务器失败

核心问题分析

你的代码存在两个关键错误:

  • 直接将base64字符串作为file字段值传入FormData,服务器无法识别为合法的文件格式
  • 手动设置Content-Type: multipart/form-data,覆盖了axios自动生成的包含boundary的请求头,导致服务器无法正确解析表单数据

修正后的代码实现

const [image, setImage] = useState(null);

const pickImageProfile = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    aspect: [3, 4],
    quality: 1,
    // 不需要base64,直接用本地URI即可
  });

  if (!result.canceled) {
    const selectedAsset = result.assets[0];
    setImage(selectedAsset.uri);
    fdata.client_image = selectedAsset.uri;

    const formData = new FormData();
    // 按照React Native FormData要求构造文件对象
    formData.append('file', {
      uri: selectedAsset.uri,
      name: `image_${Date.now()}.${selectedAsset.type.split('/')[1]}`,
      type: selectedAsset.type,
    });

    axios.post("https://myserverforimg/upload", formData)
      .then((response) => {
        console.log('上传成功:', response);
        // 这里可以拿到服务器返回的图片URL,比如 response.data.url
      }).catch((error) => {
        console.error('上传失败:', error.response?.data || error.message);
      });
  }
};

关键说明

  • FormData文件构造:React Native的FormData要求文件对象必须包含uri(本地文件路径)、name(文件名)、type(MIME类型)三个字段,这样axios才能正确封装为文件上传请求
  • 请求头自动生成:不要手动设置multipart/form-data头,axios会根据FormData自动生成包含正确boundary的请求头,这是服务器解析表单的关键
  • 可选:base64转文件方案:如果你的场景必须使用base64,可以将其转换为Blob后再添加到FormData,但在React Native中直接使用本地URI是更高效的方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:24:57