app新增接口前端传入路径获取base64

This commit is contained in:
2026-01-17 20:37:03 +08:00
parent 89a78cb5cd
commit e6b68bff8c
2 changed files with 67 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
package com.zhyc.module.app.controller;
import com.zhyc.common.config.RuoYiConfig;
import com.zhyc.common.core.domain.AjaxResult;
import com.zhyc.module.app.util.OcrRecognizeUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//图片返回base64
@RestController
@RequestMapping("/app/image")
public class ImageController {
@PostMapping
public AjaxResult getImageBase64(String path) {
// 添加空值检查
if (path == null || path.trim().isEmpty()) {
return AjaxResult.error("路径不能为空");
}
path = path.replace("/profile", "");
try {
// 构建完整的文件路径
String fullPath = RuoYiConfig.getProfile() + path;
// 读取文件并转换为字节数组
byte[] fileBytes = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(fullPath));
// 将字节数组转换为base64字符串
String base64String = java.util.Base64.getEncoder().encodeToString(fileBytes);
// 获取文件扩展名以确定MIME类型
String mimeType = getMimeType(path);
// 返回base64数据格式为 data:image/xxx;base64,xxxxx
String result = "data:" + mimeType + ";base64," + base64String;
return AjaxResult.success(result);
} catch (Exception e) {
return AjaxResult.error("读取图片失败: " + e.getMessage());
}
}
/**
* 根据文件扩展名获取MIME类型
*/
private String getMimeType(String fileName) {
String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
switch (extension) {
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "gif":
return "image/gif";
case "bmp":
return "image/bmp";
default:
return "image/jpeg"; // 默认返回jpeg类型
}
}
}

View File

@@ -8,6 +8,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
//文字识别
@RestController @RestController
@RequestMapping("/ocr") @RequestMapping("/ocr")
public class OrcController { public class OrcController {