修改管理员头像接口
<p>//1.优化修改头像接口代码
@PostMapping('/updateOneAdminByIdByFile')
public Result<Object> updateOneAdminByIdByFile(@RequestParam(value = 'file', required = false) MultipartFile file,
@RequestParam(value = 'adminId', required = false) Long adminId,
HttpServletRequest request) throws IOException {
//权限验证
String token = (String) request.getAttribute('claims_admin');
if (StringUtils.isEmpty(token)) {
log.info('token为空,权限不足!');
throw new RuntimeException('权限不足!');
}</p>
<pre><code>//查询需要修改的管理员对象
Admin admin = adminService.queryOneAdminByID(adminId);
if (admin == null) {
log.info('没查到当前用户!');
return new Result<>(ResultCode.FAIL);
}
//删除之前的头像
if (!StringUtils.isEmpty(admin.getAvatarUrl())) {
String picName = StringUtils.substringAfterLast(admin.getAvatarUrl(), '/');
if (!'1.jpg'.equals(picName)) {
String path = realPath + picName;
File file1 = new File(path);
if (!file1.exists()) {
log.info('文件' + path + '不存在,删除失败!');
} else if (file1.isFile()) {
log.info(file1.delete() ? '删除头像成功!' : '删除头像失败!');
}
}
}
//上传新头像
if (file == null || file.isEmpty()) {
log.info('文件为空!');
return new Result<>(ResultCode.FAIL);
}
String fileName = file.getOriginalFilename();
String type = StringUtils.substringAfterLast(fileName, '.');
if (!StringUtils.equalsIgnoreCase('gif', type) && !StringUtils.equalsIgnoreCase('png', type) && !StringUtils.equalsIgnoreCase('jpg', type)) {
log.info('不是我们想要的文件类型,请按要求重新上传');
return new Result<>(ResultCode.FAIL);
}
// 自定义的文件名称
String pdNo = UUID.randomUUID().toString().replaceAll('-', '');
String trueFileName = pdNo + '-' + LocalDate.now() + '.jpg';
String path = realPath + trueFileName;
File dest = new File(path);
if (!dest.getParentFile().exists() && !dest.getParentFile().mkdir()) {
log.info('创建文件夹失败!');
return new Result<>(ResultCode.FAIL);
}
file.transferTo(dest);
//更新管理员对象并保存
String avatarUrl = request.getScheme() + '://' + request.getServerName() + ':' + request.getServerPort() + '/download/' + trueFileName;
admin.setAvatarUrl(avatarUrl);
int ret = adminService.updateOneAdminByID(admin);
if (ret > 0) {
log.info('修改管理员成功!' + admin);
return new Result<>(ResultCode.SUCCESS);
} else {
log.info('修改管理员失败!');
return new Result<>(ResultCode.FAIL);
}
</code></pre>
<p>}</p>
<p>//2.代码优化说明
1)使用StringUtils工具类代替原来的判断字符串是否为空的方法,使代码更加简洁。
2)将删除头像和上传新头像的代码分开,提高代码的可读性和可维护性。
3)将获取当前日期的代码改为使用LocalDate.now(),简化代码。
4)将创建文件夹的代码逻辑改为一行代码,使代码更加简洁。
5)修改头像保存的方式,使其更加规范。</p>
原文地址: https://www.cveoy.top/t/topic/oubw 著作权归作者所有。请勿转载和采集!