需要导入这个jia包:import sun.misc.BASE64Decoder;
/**
* 上传头像
*
* @throws FileNotFoundException
* @throws IOException
*/
@RequestMapping("/jieShou")
public String GenerateImage(String tup) throws FileNotFoundException { //tup前台传过来的base64编码
String ret_fileName = null;
byte[] b1 = null;
BASE64Decoder decoder = new BASE64Decoder();
SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal(); //用的shiro框架获取当前登录用户
// 获取跟目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists())
path = new File("");
File upload = new File(path.getAbsolutePath(), "/statics/userImg");
if (!upload.exists())
upload.mkdirs();
String file_path = upload.getAbsolutePath();
if (tup == null) // 图像数据为空
return "图像数据为空";
try {
if (tup.indexOf("data:image/jpeg;base64,") != -1) {
b1 = decoder.decodeBuffer(tup.replaceAll("data:image/jpeg;base64,", ""));
} else {
if (tup.indexOf("data:image/png;base64,") != -1) {
b1 = decoder.decodeBuffer(tup.replaceAll("data:image/png;base64,", ""));
} else {
b1 = decoder.decodeBuffer(tup.replaceAll("data:image/jpg;base64,", ""));
}
}
for (int i = 0; i < b1.length; ++i) {
if (b1[i] < 0) {// 调整异常数据
b1[i] += 256;
}
}
// 生成jpeg图片,图片名称,此处可自定义,我获取的是数据库登录用户名+自增id
ret_fileName = userEntity.getUsername() + userEntity.getUserId() + ".jpg";
File file = new File(file_path + "/" + ret_fileName);
OutputStream out = new FileOutputStream(file);
out.write(b1);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
userEntity.setUserImg(ret_fileName);
sysUserService.updateCode(userEntity); //更新图片
return ret_fileName;
}