在 src/main/resources/application.yml 增加如下配置:
avatar:
root-path: D:/avatar-storage/
max-size: 2MB
allowed-types: jpg,png,jpeg,webp
UserAvatarController,实现:
POST /user/avatar/upload:接收 MultipartFile,校验类型/大小,仅允许当前用户上传,调用 Service 处理,返回 R<String>(data 字段为相对路径,例如 userId/timestamp.ext)。未经认证时返回 R.fail(401, "未认证", null)。GET /user/avatar/{userId}:根据 userId 查询头像相对路径,返回图片流,找不到或文件不存在返回404。Controller 会尝试用 Files.probeContentType 标定 Content-Type。UserAvatarService 及实现类:UserAvatarServiceImpl,负责:
{root}/{userId}/{timestamp}.{ext})、文件校验(由 FileUtils 验证类型与大小)、保存本地、数据库 avatar 字段更新。若发生参数异常(如文件类型或大小),服务抛出 CustomException 并使用 ErrorCode.PARAMETER_ERROR 返回前端。UserInfo 实体已含 avatar 字段,无需变更。AvatarProperties 配置类,前缀 avatar:root-path、max-size、allowed-types,maxSize 默认 2MB,allowedTypes 默认为 jpg,png,jpeg,webp。如需详细开发步骤可进一步细化。