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

React Native:Multipart/form-data上传图片报400错误如何解决?

问题分析与解决

核心问题

你的代码里把文件对象用JSON.stringify()转成了字符串传给FormData,导致后端接收到的是一段JSON文本,而非预期的二进制文件,这就是400错误的根源。从你提供的Form Data内容也能看出,file字段的值是JSON字符串,不是文件流。

另外,手动设置Content-Type: multipart/form-data也存在问题——axios会自动生成包含正确boundary的Content-Type头,手动设置会丢失boundary信息,导致后端无法正确解析表单数据。

修复后的代码

import {launchImageLibrary} from 'react-native-image-picker';
import { Platform } from 'react-native';

const openImageLibrary = async () => {
    const options = {
      mediaType: 'photo',
    };

    const response = await new Promise(resolve => {
      launchImageLibrary(options, resolve);
    });

    if (!response || !response.assets?.[0]) {
      return null;
    }

    const source = {uri: response.assets[0].uri};
    const {type, uri, name} = response.assets[0];
    setImageSource(source);

    const formData = new FormData();

    formData.append('id', data.id);
    formData.append('isPrimary', 'true');
    // 关键修复:直接传入文件对象,不要JSON.stringify
    formData.append('file', {
      uri: Platform.OS === 'ios' ? uri.replace('file://', '') : uri,
      type: type,
      name: name || 'image.jpg',
    });

    try {
      const uploadResponse = await axios.post(
        'my-api-url',
        formData,
        {
          // 移除手动设置的Content-Type,让axios自动处理
          headers: {
            // 可保留其他必要请求头,比如Authorization
          },
        },
      );

      console.log('Upload successful', uploadResponse.data);
    } catch (error) {
      console.error('Upload error', error);
    }
  };

额外说明

  • iOS上的uri可能带有file://前缀,部分后端无法识别,需要替换为纯路径。
  • 确保name字段有值,如果react-native-image-picker返回的name为空,可手动指定默认文件名。
  • 如果后端要求文件字段名不是file,需对应修改formData.append的第一个参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:25:23