当前位置: 首页 > news >正文

java上传base64数据流的本地存储并返回给前端URL接口实现

需求背景:前端调用接口,传给后台一个base64格式的数据流图片,后台需要实现解析数据流,转为图片,本地存储(测试阶段),并将URL返回给前端,前端可以通过浏览器等形式访问。前后端框架为若依spring boot架构。

代码开发:

1.配置 application.yml

# Spring配置
spring:# 资源信息messages:# 国际化资源文件路径basename: i18n/messagesprofiles:active: dev# 文件上传servlet:multipart:# 单个文件大小max-file-size: 150MB# 设置总上传的文件大小max-request-size: 500MB
#设置图片保存路径
image:upload-dir: uploads/imagesaccess: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);}// 返回访问URLreturn 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;@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/images/**").addResourceLocations("file:" + uploadPath + "/");}
}

 

5.apipost测试调用

 

6.浏览器访问测试。

 

至此,该接口开发及自测完毕。

http://www.dtcms.com/a/252806.html

相关文章:

  • Vue的路由配置我们平时需要去手动配置吗?还是说默认配置就可以了
  • Kafka 向 TDengine 写入数据
  • CSS3 渐变效果
  • Android及Harmonyos实现图片进度显示效果
  • 百度垂搜数据管理系统弹性调度优化实践
  • AI办公提效,Deepseek + wps生成ppt
  • 基于Java的Excel列数据提取工具实现
  • FastGPT、百度智能体、Coze与MaxKB四大智能体平台在政务场景下的深度对比
  • 【人工智能下的智算网络】广域网优化
  • 双token三验证(Refresh Token 机制​)
  • 冒泡排序C语言版
  • 极大补充ggplot2的统计分析能力
  • 使用WinUSB读写USB设备
  • 使用s3cmd 2.x 与 Cyberduck 管理在 DigitalOcean Spaces 对象存储中的数据
  • 跨语言RPC:使用Java客户端调用Go服务端的JSON-RPC服务
  • 性能测试|数据说话!在SimForge平台上用OpenRadioss进行汽车碰撞仿真,究竟多省时?
  • Leetcode-​713. 乘积小于 K 的子数组​
  • 45-Oracle 索引的新建与重建
  • phpstorm无缝切换vscode
  • Synopsys:Verification Continuum Platform介绍
  • python追加合并excel效率记录
  • 从C++编程入手设计模式——外观模式
  • C/C++中的位段(Bit-field)是什么?
  • [特殊字符]华为总部参观预约|企业通道揭秘
  • 《OpenAI Whisper模型深度研究报告:技术、应用与展望》
  • [驱动开发篇] SPI 驱动开发 - 原理解析篇
  • Vue-7-前端框架Vue之应用基础从Vue2语法到Vue3语法的演变
  • 神经体积记忆架构(NVM)-实现机械狗自主爬楼梯、跨缝隙、翻障碍
  • 《Whisper:OpenAI的先进语音识别模型》
  • Hadoop 版本进化论:从 1.0 到 2.0,架构革命全解析