本文最后更新于 2026年1月16日 下午
上传头像接口的实现
上传头像接口的需求
在个人中心点击编辑的时候可以上传头像图片
只能上传png,jpg,gif格式的文件,不大于2M
上传完头像后 可以用于更新个人信息接口
同时使用OSS(Object Storage Service)来存储头像
本项目暂时使用七牛云的对象存储服务(因为免费)
参数值为img,要上传的图像
请求头:Content-Type :multipart/form-data
UploadController类
1 2 3 4 5 6 7 8 9 10 11
| @RestController public class UploadController { private UploadService uploadService; @PostMapping("/upload") public String uploadImg(MultipartFile img) { return uploadService.uploadImg(img); } }
|
UploadService接口
1 2 3 4
| public interface UploadService {
String uploadImg(MultipartFile img); }
|
OssUploadServiceImpl实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| @Service @Data @ConfigurationProperties(prefix = "oss") public class OssUploadServiceImpl implements UploadService { private String accessKey; private String secretKey; private String bucket;
@Override public ResponseResult uploadImg(MultipartFile img) { String originalFilename = img.getOriginalFilename(); if (!originalFilename.endsWith(".png") || originalFilename.endsWith(".jpg") || originalFilename.endsWith(".gif")) { throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR); } String filePath = PathUtils.generateFilePath(originalFilename); String url = uploadOss(img, filePath); return ResponseResult.okResult(url); }
private String uploadOss(MultipartFile imgFile, String filePath) { Configuration cfg = new Configuration(Region.autoRegion()); cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2; UploadManager uploadManager = new UploadManager(cfg); String key = filePath; try { InputStream inputStream = imgFile.getInputStream(); Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(inputStream,key,upToken,null, null); DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); System.out.println(putRet.key); System.out.println(putRet.hash); return "http://t8ul2nlc8.hn-bkt.clouddn.com/" + key; } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { } } } catch (Exception ex) { } return key; } }
|
文件存储工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public class PathUtils { public static String generateFilePath(String fileName){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/"); String datePath = sdf.format(new Date()); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); int index = fileName.lastIndexOf("."); String fileType = fileName.substring(index); return new StringBuilder().append(datePath).append(uuid).append(fileType).toString(); } }
|
PS:该系列只做为作者学习开发项目做的笔记用
不一定符合读者来学习,仅供参考
预告
后续会记录博客的开发过程
每次学习会做一份笔记来进行发表
“一花一世界,一叶一菩提”
版权所有 © 2025 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/