版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ydk888888/article/details/77045252
在Controller中
@ResponseBody
@RequestMapping(value = "/avatarUploadByBase64.json", method = RequestMethod.POST)
@ApiOperation(value = "头像上传", notes = "头像上传", position = 5)
public ResponseModel<FileUploadBean> avatarUploadByBase64(HttpServletRequest request,
@ApiParam(name = "base64", value = "base64字符串") @RequestParam String base64,
@ApiParam(name = "userId", value = "用户ID") @RequestParam String userId) {
String sysFilePath = request.getSession().getServletContext().getRealPath("/");
GenerateImage(base64, sysFilePath + "/" + userId + ".jpg");
File file = new File(sysFilePath + "/" + userId + ".jpg");
if (file == null) {
return new ResponseModel(false, com.hofon.common.domain.BaseResultCode.PARAM_EMPTY.getMsg(), com.hofon.common.domain.BaseResultCode.PARAM_EMPTY.getCode());
}
FileUploadBean fileUploadBean = new FileUploadBean();
try {
// String filePath = FileUploadUtils.fileUpload(request, file, x, y, width);
String filePath = FileUploadUtils.fileUpload(file);
fileUploadBean.setFilePath(filePath);
fileUploadBean.setUploadTime(new Date());
file.delete();
Map<String, Object> params = new HashMap<>();
params.put("userId", userId);
params.put("avatar", filePath);
//healthBaseManager.updateAvatarByUserId(params);
} catch (IOException e) {
LOGGER.error("文件上传失败", e);
return new ResponseModel(false, com.hofon.common.domain.BaseResultCode.SYSTEM_ERROR.getMsg());
}
return new ResponseModel(fileUploadBean);
}
// base64 转成图片
public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}