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

Java Spring Boot中如何将MultipartFile图片转Base64存入DB并在前端主页面展示

Spring Boot 实现MultipartFile图片转Base64存取+前端展示方案

一、前置注意事项

先做方案选型提醒:Base64编码后的内容会比原文件体积大1/3左右,仅适合1M以内的小图场景,大图优先选择存对象存储服务、数据库仅存访问链接更合理。

  • 数据库存储Base64的字段类型需要匹配:MySQL场景推荐用TEXT或LONGTEXT,不要用VARCHAR避免长度不足报错。
  • 不需要额外引入第三方依赖,Spring Boot + JDK8及以上环境自带所需工具类。

二、MultipartFile 转 Base64 并存入数据库

注意要使用JDK8及以上自带的java.util.Base64工具类,不要使用废弃的sun.misc.BASE64Encoder,避免兼容性问题

代码示例:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.util.Base64;

@PostMapping("/upload/image")
public Result uploadImage(@RequestParam("file") MultipartFile file) throws Exception {
    // 1、基础参数校验
    if (file.isEmpty()) {
        return Result.fail("上传文件不能为空");
    }
    String fileContentType = file.getContentType();
    if (fileContentType == null || !fileContentType.startsWith("image/")) {
        return Result.fail("仅支持上传图片类型文件");
    }

    // 2、MultipartFile转Base64,直接拼接展示所需前缀,减少后续前端处理逻辑
    byte[] fileBytes = file.getBytes();
    String base64Content = "data:" + fileContentType + ";base64," 
                            + Base64.getEncoder().encodeToString(fileBytes);

    // 3、存入数据库,示例为MyBatis-Plus写法,可替换为自己的持久层逻辑
    ImageInfo imageInfo = new ImageInfo();
    imageInfo.setBase64Content(base64Content);
    imageInfo.setFileName(file.getOriginalFilename());
    imageInfoMapper.insert(imageInfo);

    return Result.ok(imageInfo.getId());
}

三、从数据库读取Base64返回给前端

代码示例:

@GetMapping("/get/image/{id}")
public Result getImageBase64(@PathVariable("id") Long imageId) {
    ImageInfo imageInfo = imageInfoMapper.selectById(imageId);
    if (imageInfo == null) {
        return Result.fail("图片不存在");
    }
    // 直接返回拼接好前缀的Base64字符串即可
    return Result.ok(imageInfo.getBase64Content());
}

如果是列表页需要批量返回图片,直接把Base64字段加到列表返回实体的对应属性中即可。


四、前端页面展示Base64图片

Base64图片是标准格式,所有前端框架都可以直接赋值给img标签的src属性展示:

原生JS示例

<img id="targetImg" alt="图片展示" />
<script>
// 调用后端接口拿到返回的Base64字符串
fetch('/get/image/1').then(res => res.json()).then(data => {
    document.getElementById('targetImg').src = data.data;
})
</script>

Vue示例

<template>
  <img :src="imgBase64" alt="图片展示" />
</template>
<script>
export default {
  data() {
    return {
      imgBase64: ''
    }
  },
  mounted() {
    // 调用接口获取Base64
    this.axios.get('/get/image/1').then(res => {
      this.imgBase64 = res.data.data
    })
  }
}
</script>

额外优化建议

  • 上传前可以用Thumbnails等工具类对图片做压缩处理,减少Base64长度
  • 存储时可以对Base64字符串做Gzip压缩,读取时再解压,减少数据库存储占用
  • 超过1M的图片不建议用该方案,优先对接OSS、MinIO等对象存储服务

内容的提问来源于stack exchange,提问作者Ahmed Mohamed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:00:04