Spring Boot整合Thymeleaf上传图片报类型不匹配异常排查
报错原因
核心是类型绑定错误,两个配置问题共同导致异常:
- 前端文件选择框错误绑定了字符串类型字段:你在文件input上写了
th:field="*{imageName}",Thymeleaf会把上传的MultipartFile文件对象直接映射到Product实体的imageName属性(该属性是String类型),Spring没有内置文件对象转字符串的转换器,直接抛出类型不匹配异常。你自己代码里都注释掉了这行绑定,实际却没删掉,属于手滑漏改。 - 前后端文件参数名不匹配:后端Controller用
@RequestParam("file")接收文件,但前端input的name属性写的是image,就算类型绑定没问题,后端也接不到上传的文件。
修复方法
1. 修改前端表单
删掉文件输入框上的th:field属性,把name值改成file和后端参数对应。imageName是你后端拿到文件后自己处理生成、再set到Product里的,不需要前端传值绑定:
<form action="#" th:action="@{/showNewProductForm}" th:object="${saved}" method="post" enctype="multipart/form-data"> <p>Name: <input type="text" th:field="*{name}" /></p> <p>Category: <input type="text" th:field="*{category}" /></p> <p>Image: <input name="file" type="file" accept="image/png, image/jpg, image/jpeg"/></p> <p>Description: <input type="text" th:field="*{description}" /></p> <button type="submit" value="Submit">Save Product</button> </form>
2. 可选补全校验
给上传接口加个文件空值判断,避免用户没选文件就提交触发空指针:
@PostMapping("/showNewProductForm") public String addAProduct(@ModelAttribute Product product, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "请先选择要上传的图片"); return "redirect:/showNewProductForm"; } productService.saveProduct(product, file); redirectAttributes.addFlashAttribute("message", "产品 " + product.getName() + " 上传成功!"); return "redirect:/showNewProductForm"; }
你原来写的Service层文件存储、文件名生成逻辑没有问题,不需要改动,改完上面两处重启服务就能正常运行。
内容的提问来源于stack exchange,提问作者iTchTheRightSpot
相关产品推荐
相关产品推荐

