如何解决Spring Boot接口MultipartFile为空时返回500错误的问题
问题根因
- 你遇到的500错误发生在Controller参数绑定阶段,没有进入你方法内部的try-catch块,因此异常没有被捕获。
@RequestPart注解要求请求必须为multipart/form-data类型,且当请求中没有文件段时,Spring对非文件类型的@RequestPart参数解析会直接失败。 - 你当前代码中调用
service.addProject传入的request、response未在方法形参中声明,若不是类成员变量也会触发运行时错误;且异常场景下responseJsonObject为null,返回时也会触发空指针异常。
修复步骤
1. 调整Controller接口代码
将非文件参数的注解从@RequestPart改为@RequestParam,手动做JSON转换,同时补全必要的形参、处理返回值的空指针问题:
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @PostMapping(value = "add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<JSONObject> addProject( @RequestParam(required = false, value = "file") MultipartFile file, @RequestParam(value = "jsonObject", required = false) String jsonObjectStr, HttpServletRequest request, HttpServletResponse response) { JSONObject responseJsonObject = new JSONObject(); try { // 手动转换JSON字符串为对象 JSONObject jsonObject = jsonObjectStr != null ? JSON.parseObject(jsonObjectStr) : null; responseJsonObject = service.addProject(request, response, file, jsonObject); } catch (Exception e) { LOGGER.error("Error in addProject() method !!", e); responseJsonObject.put("code", 500); responseJsonObject.put("message", "服务内部错误"); } return ResponseEntity.status(HttpStatus.CREATED).body(responseJsonObject); }
2. 新增Multipart配置
在项目配置文件中添加配置,支持无文件的Multipart请求:
application.yml 配置
spring: servlet: multipart: enabled: true resolve-lazily: true # 延迟解析,允许请求中没有文件 max-file-size: 10MB max-request-size: 100MB
application.properties 配置
spring.servlet.multipart.enabled=true spring.servlet.multipart.resolve-lazily=true spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=100MB
3. Postman请求调整
无论是否上传文件,请求Body都选择form-data类型:
- 传文件时,正常添加
file字段选择文件,添加jsonObject字段填入JSON字符串即可 - 不传文件时,仅保留
jsonObject字段填入JSON字符串即可,无需其他额外配置
内容的提问来源于stack exchange,提问作者Akhil Nallapaneni
相关产品推荐
相关产品推荐

