『博客开发日记』之上传头像接口的实现

本文最后更新于 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
//Oss上传图片实现类
@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();
//判断文件名是否为png,jpg,gif
if (!originalFilename.endsWith(".png") || originalFilename.endsWith(".jpg") || originalFilename.endsWith(".gif"))
{
throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
}
//如果判断通过就上传到Oss
String filePath = PathUtils.generateFilePath(originalFilename);
String url = uploadOss(img, filePath); //文件储存方式为:yyyy/MM/dd/文件名.后缀
return ResponseResult.okResult(url);
}


private String uploadOss(MultipartFile imgFile, String filePath)
{
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.autoRegion());
cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
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);
//图片的外链不建议写死,现在为了测试方便先写死,到时候换成别的,注意这个外链链接试用30天
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) {
//ignore
}
}
} catch (Exception ex) {
//ignore
}
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){
//根据日期生成路径 2022/1/15/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
String datePath = sdf.format(new Date());
//uuid作为文件名
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//后缀和文件后缀一致
int index = fileName.lastIndexOf(".");
// test.jpg -> .jpg
String fileType = fileName.substring(index);
return new
StringBuilder().append(datePath).append(uuid).append(fileType).toString();
}
}


PS:该系列只做为作者学习开发项目做的笔记用

不一定符合读者来学习,仅供参考


预告

后续会记录博客的开发过程

每次学习会做一份笔记来进行发表

“一花一世界,一叶一菩提”


版权所有 © 2025 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/


『博客开发日记』之上传头像接口的实现
http://example.com/2026/01/14/『博客开发日记』之上传头像接口的实现/
作者
云梦泽
发布于
2026年1月14日
更新于
2026年1月16日
许可协议