public static File base64ToFile(String base64, String fileName, String localPath) throws IOException {
File file = null;
File dir = new File(localPath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
String str = base64
.replace("data:image/png;base64,", "")
.replace("data:image/jpeg;base64,", "")
.replace("data:image/jpg;base64,", "")
.replace(" ", "+");
try {
byte[] bytes = Base64.getMimeDecoder().decode(str);
file = new File(localPath + "\\" + fileName);
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
public Result uploadUserHeadImg(@NotNull String headImg, HttpServletRequest request) throws IOException {
String fileName = UUID.fastUUID() + ".png";
String userDir = System.getProperty("user.dir");
String localPath = userDir+"\\src\\main\\resources\\static\\upload\\userHeadImg";
File file = UploadUtil.base64ToFile(headImg, fileName, localPath);
String requestPath = null;
try {
requestPath = "http://" + NetworkUtils.getIpAndPort() + "/upload/userHeadImg/" + fileName;
log.info("访问路径为:{}", requestPath);
} catch (Exception e) {
e.printStackTrace();
}