一:依赖安装
<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/");
}
}