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

React Native向Spring Boot后端发送图片时后端接收为null的问题求助

React Native向Spring Boot后端发送图片时后端接收为null的问题求助

我最近碰到个棘手的问题,想请大家帮忙看看!具体情况是这样的:

  • 我在React Native移动端向Spring Boot后端发送包含图片参数的API请求时,后端那边的图片参数始终是null
  • 但用Postman发送完全相同的请求参数时,后端就能正常接收到图片

以下是我写的请求代码片段:

export const createGroupApiAction = async (
  createGroupRequestDTO: CreateGroupRequestDTO,
  token: string
): Promise<Group> => {
  // Create a FormData object to handle the file and text data
  const formData = new FormData();

  formData.append('userId', createGroupRequestDTO.userId);
  formData.append('userName', createGroupRequestDTO.userName);
  formData.append('groupName', createGroupRequestDTO.groupName);
  formData.append('groupDescription', createGroupRequestDTO.groupDescription);
  formData.append('isPublic', createGroupRequestDTO.isPublic.toString());
  formData.append('isPaid', createGroupRequestDTO.isPaid.toString());
  formData.append('price', createGroupRequestDTO.price?.toString() || '');

  // 处理图片参数
  if (createGroupRequestDTO.groupImage) {
    formData.append('groupImage', {
      uri: createGroupRequestDTO.groupImage.uri,
      name: createGroupRequestDTO.groupImage.name || 'group-image.jpg',
      type: createGroupRequestDTO.groupImage.type || 'image/jpeg'
    } as any);
  }

  try {
    const response = await axios.post<Group>(
      `${API_BASE_URL}/groups`,
      formData,
      {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'multipart/form-data'
        }
      }
    );
    return response.data;
  } catch (error) {
    throw handleApiError(error);
  }
};

我自己琢磨了好久,还是没找到问题根源,猜测可能是这几个地方出了问题:

  • FormData图片格式处理:React Native的FormData处理文件和Web端不太一样,是不是我对图片uri的格式处理不对?比如iOS的uri是file://开头,Android是content://,有没有可能需要做转换?或者name、type的设置不符合要求?
  • 请求头Content-Type设置:听说axios在发送FormData时会自动添加正确的boundary,手动设置multipart/form-data反而会导致boundary缺失?是不是应该去掉手动设置的这个请求头?
  • 后端接收逻辑:我后端用@RequestParam("groupImage") MultipartFile groupImage接收参数,参数名和前端是一致的,Postman能成功应该不是这个问题,但有没有可能还有其他细节没注意到,比如MultipartResolver的配置?

有没有小伙伴遇到过类似的情况,或者能给点排查方向呀,实在卡在这里动不了了😥

备注:内容来源于stack exchange,提问作者pritam pawar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 12:34:32