base64编码 springboot_springboot接收上传base64图片

该博客介绍了如何在SpringBoot应用中接收并处理Base64编码的图片,通过将Base64字符串解码并保存为文件,然后更新用户信息中的头像路径。
摘要由CSDN通过智能技术生成

@ApiOperation(value = "更新用户信息", notes = "更新用户信息,包括手机号、邮箱、头像等", httpMethod = "GET")

@PostMapping("/profile")

public ApiResult profile(@RequestBody SysUserVo sysUserVo) {

Boolean result = false;

String imageRelativePath = "static/upload";

String imageBase64Str;

Integer userId = UserUtil.getUserId(request);

//如果相同

if (userId > 0) {

//保存头像

StringBuffer fileName = new StringBuffer();

fileName.append(UUID.randomUUID().toString().replaceAll("-", ""));

if (StringUtils.isBlank(sysUserVo.getAvatar())) {

return new ApiResult<>(false);

} else if (sysUserVo.getAvatar().indexOf("data:image/png;") != -1) {

imageBase64Str = sysUserVo.getAvatar().replace("data:image/png;base64,", "");

fileName.append(".png");

} else if (sysUserVo.getAvatar().indexOf("data:image/jpeg;") != -1) {

imageBase64Str = sysUserVo.getAvatar().replace("data:image/jpeg;base64,", "");

fileName.append(".jpeg");

} else {

return new ApiResult<>(false);

}

File path;

try {

path = new File(ResourceUtils.getURL("classpath:").getPath());

if (!path.exists()) {

path = new File("");

}

File uploadPath = new File(path.getAbsolutePath(), imageRelativePath);

if (!uploadPath.exists()) {

uploadPath.mkdirs();

}

String relativeFile = imageRelativePath+"/"+fileName.toString();

File file = new File(uploadPath, fileName.toString());

byte[] fileBytes = Base64.getDecoder().decode(imageBase64Str);

FileUtils.writeByteArrayToFile(file, fileBytes);

sysUserVo.setUserId(userId);

sysUserVo.setAvatar(relativeFile);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

return new ApiResult<>(false);

}

//更新用户信息

result = sysUserService.updateInfoByUserId(sysUserVo);

}

return new ApiResult<>(result);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值