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

React Native中axios构造FormData上传图片无更新问题排查

React Native 图片上传功能失效修复

问题现象

使用react-native-image-picker选择图片后调用上传接口,接口无数据更新,但同接口在Postman中可正常调用。Postman调用示例如下:
接口调用示例

根因定位

代码存在4处直接导致上传失败的问题:

  • FormData参数错误:仅向image字段传入了文件名字符串,未传入实际图片文件对象,和Postman的文件传参格式完全不一致
  • 请求头缺失配置:未指定Content-Type: multipart/form-data,且未禁用axios的默认序列化逻辑,导致FormData被错误转码
  • 跨平台兼容问题:iOS端返回的图片URI未做协议适配,可能出现系统无法读取本地文件的情况
  • 状态码判断逻辑错误:result.status是HTTP状态码(数值类型),不可能返回字符串success,该判断条件无效

修复方案

1. 修正图片选择逻辑

补全跨平台URI适配、文件类型/文件名兜底逻辑:

import { Platform } from 'react-native';

const handlePickImage = () => {
  launchImageLibrary(
    {
      mediaType: 'photo',
      quality: 0.5,
    },
    (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
        return;
      }
      if (response.error) {
        console.log('ImagePicker Error: ', response.error);
        return;
      }
      if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
        return;
      }

      const asset = response?.assets?.[0];
      if (!asset?.uri) {
        console.log('Fail to pick image!');
        return;
      }

      // 兼容iOS/安卓URI格式
      const fixedUri = Platform.OS === 'ios' ? asset.uri.replace('file://', '') : asset.uri;
      // 兜底文件类型、文件名,避免空值导致上传失败
      const fileType = asset.type || 'image/jpeg';
      const fileName = asset.fileName || `${formik.values.companyName.replace(/\s/g, '-')}.jpg`;

      setSelectedImage({
        name: fileName,
        uri: fixedUri,
        type: fileType,
      });
      setPreviewImage(asset.uri);
    },
  );
};

2. 修正FormData组装与提交逻辑

传入完整文件对象,补齐请求头配置,修正状态码判断:

// 组装FormData:传入完整文件对象,而非仅传文件名
const formData = new FormData();
formData.append('image', {
  uri: selectedImage.uri,
  name: selectedImage.name,
  type: selectedImage.type,
});

await handleSubmit(formData);

const handleSubmit = async (input) => {
  try {
    const result = await axios.patch(`${BASE_URL}/company/profile`, input, {
      headers: {
        Authorization: `Gosnix ${DataLoginReducers?.token}`,
        'Content-Type': 'multipart/form-data',
      },
      // 禁止axios默认序列化FormData
      transformRequest: (data) => data,
    });

    // 修正状态码判断逻辑
    if ([200, 201].includes(result.status)) {
      formik.resetForm();
      setModalActive({ status: false });
      setErrorMessage('');
      navigation.goBack();
    }
  } catch (error) {
    // 打印详细错误信息方便排查
    console.log('Upload error:', error.response?.data || error.message);
    setModalActive({ status: true, type: 'error' });
    setErrorMessage(translations['please.try.again']);
  }
};

排查提示

如果修改后仍上传失败,可先打印selectedImage确认uri/name/type三个字段均有有效值,再通过抓包工具确认请求体中image字段为文件格式而非纯字符串。React Native 0.60及以上版本自带FormData支持,无需额外引入polyfill依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 00:24:21