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

SpringBoot实现图片存入MySQL数据库遇到问题求助

图片存入数据库失败,请求排查代码问题

我不清楚如何将图片存入数据库,尝试了以下代码但无法正常运行,麻烦帮忙排查问题:

表单代码

<form
    method="post"
    role="form"
    th:object="${newPainting}"
    th:action="@{/admin/add-new-painting}"
    th:csrf="${_csrf.token}"
    enctype="multipart/form-data">
            
    <div class="mb-3">
        <label for="img" class="form-label">Immagine quadro</label>
        <input class="form-control" type="file" id="img" name="img">
        <p th:errors="*{img}" class="text-danger" th:if="${#fields.hasErrors('img')}"></p>
    </div>      
    <div class="form-group">
        <button class="btn btn-primary"type="submit">Aggiungi</button>
    </div>
</form>

控制器代码

@PostMapping("/add-new-painting")
public String createPainting(@ModelAttribute("newPainting") @Valid Painting painting,
                             @RequestParam("img") MultipartFile imageFile,
                             BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        return "admin/add-new-painting";
    }
        
    try {
        byte[] imageData = imageFile.getBytes();
        painting.setImg(imageData);
        service.savePainting(painting);
            
        return "redirect:/admin/dashboard";
    } catch(IOException e){
        e.printStackTrace();
        
        return "Errore nel caricamento dell'immagine";
    }       
}

实体类属性

@Column(name = "img", columnDefinition = "LONGBLOB")
@Lob
private byte[] img;

排查要点

  • 参数顺序错误:BindingResult必须紧跟在@Valid注解的参数之后,当前代码将MultipartFile插在中间,导致Spring无法正确绑定验证结果,bindingResult.hasErrors()无法生效。调整后的参数顺序应为:
public String createPainting(@ModelAttribute("newPainting") @Valid Painting painting,
                             BindingResult bindingResult,
                             @RequestParam("img") MultipartFile imageFile)
  • 缺少文件非空校验:未检查用户是否选择文件,若imageFile为空,调用getBytes()会抛出异常。添加判断逻辑:
if (imageFile.isEmpty()) {
    bindingResult.rejectValue("img", "error.painting", "必须选择图片文件");
    return "admin/add-new-painting";
}
  • 错误返回逻辑不合理:catch块直接返回字符串,Spring会寻找对应视图文件,应返回表单页面并添加错误提示:
catch(IOException e){
    e.printStackTrace();
    bindingResult.rejectValue("img", "error.painting", "图片上传失败,请重试");
    return "admin/add-new-painting";
}
  • 实体类缺少验证注解:表单中的th:errors需要实体类配合验证注解才能生效,给img属性添加@NotNull注解:
@Column(name = "img", columnDefinition = "LONGBLOB")
@Lob
@NotNull(message = "图片不能为空")
private byte[] img;
  • 检查Multipart配置:确保Spring Boot配置了合理的文件上传大小限制,在application.properties中添加:
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

内容的提问来源于stack exchange,提问作者Simone Tritto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:02:50