需求背景:前端调用接口,传给后台一个base64格式的数据流图片,后台需要实现解析数据流,转为图片,本地存储(测试阶段),并将URL返回给前端,前端可以通过浏览器等形式访问。前后端框架为若依spring boot架构。
代码开发:
1.配置 application.yml
# Spring配置 spring: # 资源信息 messages: # 国际化资源文件路径 basename: i18n/messages profiles: active: dev # 文件上传 servlet: multipart: # 单个文件大小 max-file-size: 150MB # 设置总上传的文件大小 max-request-size: 500MB #设置图片保存路径 image: upload-dir: uploads/images access: base-url: http://localhost:8080/images # 图片访问的基础URL
2.Controller中获取配置文件中的URL及基础URL路径
// 从配置文件中读取图片存储路径 @Value("${image.upload-dir}") private String uploadPath; // 从配置文件中读取图片访问基础URL @Value("${image.access.base-url}") private String accessBaseUrl;
3. Controller中开发base64接口,包括解码、存储、拼接返回URL。
/** * 上传base64格式图片(单个) * @param request * @return */ @PostMapping("/api/uploadImage") public ResponseEntity<Map<String, String>> uploadImage(@RequestBody Map<String, String> request) { Map<String, String> response = new HashMap<>(); try { String base64Data = request.get("image"); if (base64Data == null || base64Data.isEmpty()) { response.put("error", "No image data provided"); return ResponseEntity.badRequest().body(response); } // 检查并创建上传目录 checkAndCreateUploadDir(); // 生成唯一文件名 String fileName = generateFileName(); // 解码并保存图片 String imageUrl = saveBase64Image(base64Data, fileName); response.put("url", imageUrl); return ResponseEntity.ok(response); } catch (Exception e) { response.put("error", "Failed to upload image: " + e.getMessage()); return ResponseEntity.internalServerError().body(response); } } /** * 加载校验图片存储地址 * @throws IOException */ private void checkAndCreateUploadDir() throws IOException { File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { Files.createDirectories(Paths.get(uploadPath)); } } /** * 生成图片名 * @return */ private String generateFileName() { return IdUtils.simpleUUID() + ".jpg"; } /** * 保存图片并返回对应URL地址 * @param base64Data * @param fileName * @return * @throws IOException */ private String saveBase64Image(String base64Data, String fileName) throws IOException { // 移除Base64前缀(如果有) String base64Image = base64Data.split(",")[1]; // 解码Base64数据 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 保存文件 String filePath = uploadPath + File.separator + fileName; try (FileOutputStream fos = new FileOutputStream(filePath)) { fos.write(imageBytes); } // 返回访问URL return accessBaseUrl + "/" + fileName; }
4.配置前端可访问的服务形式,新建WebConfig
package com.ruoyi.web.core.config; import org.springframework.beans.factory.annotation.Value; 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 { @Value("${image.upload-dir}") private String uploadPath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/images/**") .addResourceLocations("file:" + uploadPath + "/"); } }
5.apipost测试调用
6.浏览器访问测试。
至此,该接口开发及自测完毕。