Spring Boot图片上传遇‘Content type application/json not supported’错误求助
问题排查与解决方案
1. 核心错误原因:@RequestBody与Multipart请求冲突
你的接口声明了consumes=MediaType.MULTIPART_FORM_DATA_VALUE,但方法参数同时使用了@RequestBody ArtistModel Ar。@RequestBody用于解析JSON格式请求体,而multipart/form-data是表单提交格式,二者无法兼容,这就是触发Content type 'application/json' not supported错误的直接原因。
2. 修复请求参数绑定问题
将@RequestBody ArtistModel Ar替换为@ModelAttribute ArtistModel Ar,Spring会自动从multipart表单中绑定字段到ArtistModel对象:
@RequestMapping(value = "/add", method = RequestMethod.POST, consumes=MediaType.MULTIPART_FORM_DATA_VALUE ) public ResponseEntity<AGPResponse> handleFileUpload( @RequestParam("file") MultipartFile file, @ModelAttribute ArtistModel Ar ) throws ParseException { // 原有业务逻辑... }
如果表单字段与ArtistModel的属性名完全匹配,甚至可以直接省略@ModelAttribute,Spring依然能自动完成绑定:
public ResponseEntity<AGPResponse> handleFileUpload( @RequestParam("file") MultipartFile file, ArtistModel Ar ) throws ParseException {
3. 修复文件保存路径问题
你当前使用的/src/main/resources/public/resources/file是开发环境的硬编码绝对路径,项目打包部署后该路径会失效。建议通过Spring的ResourceLoader获取资源目录的真实路径:
步骤1:注入ResourceLoader
在Controller中添加依赖注入:
@Autowired private ResourceLoader resourceLoader;
步骤2:修改文件保存逻辑
替换原有的文件保存代码:
String photo = file.getOriginalFilename(); // 获取目标目录的资源对象 Resource resource = resourceLoader.getResource("classpath:public/resources/file/"); File saveDir = resource.getFile(); // 确保目录存在,不存在则创建 if (!saveDir.exists()) { saveDir.mkdirs(); } // 拼接完整文件路径并保存 File destFile = new File(saveDir, photo); file.transferTo(destFile);
如果项目打包为Jar包运行,resource.getFile()可能报错(Jar内资源并非真实文件系统路径),此时改用流写入方式:
try (OutputStream os = new FileOutputStream(resource.getFile())) { os.write(file.getBytes()); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
4. 额外注意事项
- 前端提交表单时,必须设置
enctype="multipart/form-data",否则无法正确传递文件和表单数据。 - 确保ArtistModel类的所有属性都有对应的getter/setter方法,否则Spring无法完成字段绑定。
- 可通过配置文件限制上传文件大小(application.properties):
spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB
内容的提问来源于stack exchange,提问作者hagi kassaye
相关产品推荐
相关产品推荐

