spring boot实现base64上传

一:依赖安装

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

二:base64上传示例

复制代码
package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

@RestController
@RequestMapping("/base64")
public class Base64Controller {

    private static final String UPLOAD_PATH = "upload/";

    //base64上传
    @PostMapping
    public String upload(@RequestBody Base64FileDTO dto)
    {

        String base64Str = dto.getBase64();

        if (base64Str == null || base64Str.isEmpty()) {
            return "base64不能为空";
        }

        // 去除base64前缀:data:image/png;base64,
        String[] parts = base64Str.split(",");
        String base64Content;
        if (parts.length > 1) {
            base64Content = parts[1];
        } else {
            base64Content = base64Str;
        }

        byte[] bytes;
        try {
            bytes = Base64.getDecoder().decode(base64Content);
        } catch (IllegalArgumentException e) {
            return "base64格式有误";
        }
        //定义保存文件名
        String suffix = "png";
        if (parts[0].contains("jpeg")) {
            suffix = "jpg";
        } else if (parts[0].contains("png")) {
            suffix = "png";
        } else if (parts[0].contains("gif")) {
            suffix = "gif";
        }
        String fileName = UUID.randomUUID() + "." + suffix;

        File dest = new File(UPLOAD_PATH, fileName).getAbsoluteFile();

        File dir = dest.getParentFile();
        if (!dir.exists() && !dir.mkdirs()) {
            return "上传失败:目录创建失败";
        }

        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件保存失败";
        }

        return "上传成功,文件名:" + fileName;
    }

    // DTO
    static class Base64FileDTO {
        private String base64;

        public String getBase64() {
            return base64;
        }
        public void setBase64(String base64) {
            this.base64 = base64;
        }
    }
}

三:调用base64上传示例

使用postman调用上传测试

POST:http://127.0.0.1:8080/base64

请求体 raw JSON:

复制代码
{
    "base64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}

四:配置远程访问资源

如果需要直接通过 url 访问上传图片,需要配置静态资源映射

复制代码
package com.example.demo.config;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        // 访问路径 /upload/** 映射到本地 /upload/
        registry.addResourceHandler("upload/**")
                .addResourceLocations("file:upload/");
    }
}
相关推荐
IT_陈寒19 分钟前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
Csvn43 分钟前
Nginx 与 OpenResty:阶段钩子、shared dict 与动态 upstream/证书
后端·nginx
geovindu2 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
Java与AI落地2 小时前
RAG 第二步:检索质量不行,先别换模型
后端
JavaGuide2 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
喵个咪2 小时前
RushWind Admin — 模块化单体:一个进程与通往微服务的五级阶梯
后端·架构·rust
用户69371750013843 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
Hespethorn3 小时前
文件该放在哪:十个位置、三处边界、三份声明
后端·架构
喵个咪3 小时前
RushWind CMS — 最小微服务实例:微服务架构的最小完备集
后端·架构·rust
彭亚川Allen3 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试