base64值转图片并保存在指定路径
@Slf4j
public class Base64ToPictuerUtil {
public static Map<String,Object> uploadUtil(String base64Str, String filePath, HttpSession httpSession, HttpServletResponse response) {
Map<String , Object> results = new HashMap<>();
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(base64Str.substring(base64Str.indexOf(",") + 1));
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 1024;
}
}
String fileName = UUID.randomUUID().toString().replace("-","") + ".jpg";
String fullPath= filePath + fileName;
//路径校验
try {
fullPath = this.filenameFilter(fullPath);
} catch (IllegalPathException e) {
log.warn(e.getMessage());
}
File saveFile = new File(fullPath);
File fileParent = saveFile.getParentFile();//返回的是File类型,可以调用exsit()等方法
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if (!saveFile.exists()) {
saveFile.createNewFile();//有路径才能创建文件
}
log.info(saveFile + "---------------图片保存路径");
// 写入文件到本地存储位置
out = new FileOutputStream(saveFile);
out.write(bytes);
results.put("flag",1);
results.put("filePath",saveFile.getPath());
results.put("fileName",fileName);
} catch (Exception e) {
results.put("flag", 0);
log.error("[图片保存失败] : uploadUtil fail",e);
}finally {
try {
if(out != null){
out.flush();
out.close();
}
}catch (Exception e){
log.error("流关闭失败",e);
e.printStackTrace();
}
}
return results;
}
}
/**
* 路径校验过滤
* @param path
* @return
*/
public static String filenameFilter(String path) throws IllegalPathException {
String injectListStr = "../|./|/..| |<|>|~/|?";
String[] badStrArr = injectListStr.split("\\|");
for (String badStr : badStrArr) {
if (path.contains(badStr)) {
throw new IllegalPathException("路径不合法!");
}
}
return path;
}
个人日常学习记录
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)