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

Spring Boot多文件上传:@RequestParam配置正确仍报'file'缺失异常

解决React Native/Expo上传文件到Spring Boot时的MissingServletRequestPartException异常

出现MissingServletRequestPartException: Required part 'file' is not present的核心原因是前端传递的FormData无法被Spring Boot正确解析,主要有两个关键问题:

1. 手动设置Content-Type导致boundary缺失

React Native中,手动指定Content-Type: multipart/form-data会丢失表单分隔符boundary,后端无法识别表单中的部件。axios会自动根据FormData生成包含boundary的正确Content-Type,所以必须移除手动设置的Content-Type头。

2. React Native的URI格式适配问题

iOS和Android的文件URI格式存在差异:

  • iOS的URI通常以file://开头,需要去掉该前缀才能被FormData正确识别
  • Android的URI格式无需额外处理(无论是content://还是file://都可直接使用)

修改后的前端代码

import { Platform } from 'react-native';
import axios from 'axios';

const uploadImage = async (uri: string, type: "Logo" | "Signature") => {  
  // 适配iOS和Android的URI格式
  const fixedUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
  
  const formData = new FormData();  
  formData.append("file", {  
    uri: fixedUri,  
    name: `${type}_${Date.now()}.jpg`,  
    type: "image/jpeg",  
  });  

  const endpoint = `http://localhost:8080/api2/business/${userMobile}/upload${type}`;  
  // 移除手动设置的Content-Type,axios自动生成正确的请求头
  const response = await axios.post(endpoint, formData);  
  return response.data;  
};  

后端额外检查(可选)

确保Spring Boot的multipart配置正常,默认情况下框架已开启文件上传支持,若有自定义配置,需保证spring.servlet.multipart.enabled=true,且max-file-size、max-request-size参数满足文件大小需求。

内容的提问来源于stack exchange,提问作者Abhishek Kumar Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:03:18