欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > java上传base64数据流的本地存储并返回给前端URL接口实现

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

2025/11/5 13:53:54 来源:https://blog.csdn.net/u012858008/article/details/148722382  浏览:    关键词: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.浏览器访问测试。

 

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词