java.util.Base64.getEncoder().encodeToString("进制)//编码
java.util.Base64.getDecoder().decode(字符串内容)//解码
import java.util.Base64;
import java.util.Base64.Decoder;
需要导入这两个类
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String imgName = request.getParameter("name");
String img = request.getParameter("imgbase64");
int index = img.lastIndexOf(",");
if(index != -1) {
img = img.substring(index+1);
}//去除ata:image/jpeg;base64,前缀
Decoder decode = Base64.getDecoder();
byte[] byteImg = decode.decode(img);//把base64转成字节码
System.out.println(imgName);
int hc = imgName.hashCode();
String hex = Integer.toHexString(hc);//16进制字符串
/*
* 创建文件夹
*/
String root = this.getServletContext().getRealPath("/images/user/");
System.out.println(root);
File dirFile = new File(root,"/"+hex.charAt(0)+"/"+hex.charAt(1));//取前16进制的前两个字符串创建二级目录
dirFile.mkdirs();//创建目录
String imgNewName = CommonUtils.unid()+".jpg";
OutputStream out = new FileOutputStream(dirFile+"/"+imgNewName);//保存
out.write(byteImg);//写入文件
out.flush();
out.close();
//新图片地址
String newAdd = this.getServletContext().getContextPath()+"/images/user/"+hex.charAt(0)+"\\/"+hex.charAt(1)+"\\/"+imgNewName;
System.out.println(newAdd);
response.getWriter().write("{\"src\":\""+newAdd+"\"}"); //返回到前端页面
}