上传图片不存在时的bug修改

This commit is contained in:
guoshengxiong 2025-12-12 10:09:58 +08:00
parent 243f8aa301
commit 3098077f06
4 changed files with 89 additions and 2 deletions

View File

@ -1,6 +1,7 @@
package com.zhgd.xmgl.util;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
@ -72,8 +73,14 @@ public class Base64Util {
* @param imgPath
*/
public static String convertFileToBase64(String imgPath) {
byte[] fileBytes = FileUtil.readBytes(imgPath);
return Base64.encodeBase64String(fileBytes);
try {
byte[] fileBytes = FileUtil.readBytes(imgPath);
return Base64.encodeBase64String(fileBytes);
} catch (IORuntimeException e) {
log.debug("",e);
log.error("本地文件图片、excel等转换成Base64字符串错误:{}",e.getMessage());
}
return null;
}
/**

View File

@ -0,0 +1,36 @@
package com.zhgd.xmgl.util;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mockStatic;
@ExtendWith(MockitoExtension.class)
class Base64UtilTest {
@Test
void convertFileToBase64_Success() {
String imgPath = TestResourceUtils.getTestImgPath();
// 执行测试
String result = Base64Util.convertFileToBase64(imgPath);
// 验证结果
assertNotNull(result);
}
@Test
void convertFileToBase64_FileReadError() {
String imgPath = "不存在.jpg";
// 执行测试
String result = Base64Util.convertFileToBase64(imgPath);
// 验证结果
assertNull(result);
}
}

View File

@ -0,0 +1,44 @@
package com.zhgd.xmgl.util;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Paths;
public class TestResourceUtils {
/**
* 获取测试图片路径
*
* @return
*/
@NotNull
public static String getTestImgPath() {
// classpath 获取测试文件路径
ClassLoader classLoader = TestResourceUtils.class.getClassLoader();
URL resourceUrl = classLoader.getResource("images/test.jpg");
if (resourceUrl == null) {
throw new RuntimeException("测试图片文件未找到: images/test.jpg");
}
try {
// 使用 URI 方式处理 URL 编码 %20
URI uri = resourceUrl.toURI();
return Paths.get(uri).toAbsolutePath().toString();
} catch (URISyntaxException e) {
// 回退方案使用 URLDecoder 解码
try {
String decodedPath = URLDecoder.decode(resourceUrl.getFile(), "UTF-8");
return new File(decodedPath).getAbsolutePath();
} catch (UnsupportedEncodingException e2) {
throw new RuntimeException("路径解码失败", e2);
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 655 B