package com.hlkj.electricity.util;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.UUID;
/**
*
* 将图片的base64编码转变成图片上传到服务器
* @author liubo
* @date 2022/12/8 09:13
*/
@Log4j2
@Component
public class Base64ImageUtils {
/**
* 文件上传路径
*/
@Value("${path.uploadBasePath}")
private String uploadBasePath;
/**
* 文件回显路径
*/
@Value("${path.showPath}")
private String showPath;
/**
* 返回回显路径进行保存
* @param imagePath
* @return
* @author liubo
*/
public String uploadFile(String imagePath){
// 生成图片路径和文件名
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
String path = "/"+year+month+"/";
//base64编码转换
Base64 decoder = new Base64();
byte[] b = decoder.decode(imagePath);
// 调整异常数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
//文件目录不存在创建目录
File file = new File(uploadBasePath + path);
if (!file.exists()) {
file.mkdirs();
}
//文件名称
String fileName = UUID.randomUUID().toString().replaceAll("-","")+".png";
//文件上传
try(FileOutputStream out = new FileOutputStream(uploadBasePath + path + fileName)){
out.write(b);
out.flush();
out.close();
}catch (Exception e){
log.error("文件上次失败==[{}]",e);
}
log.info("文件上传成功!");
String uploadPath = showPath + path +fileName;
log.info("图片回显路径==[{}]",uploadPath);
return uploadPath;
}
}