feat: 头像文件存储到服务器

- 登录时自动下载微信头像到服务器
- 手动上传头像保存到服务器
- 数据库存储服务器上的头像路径
- 添加downloadAvatar方法处理头像下载
This commit is contained in:
H1d3rOne committed 2026-03-10 06:34:28 +08:00
1 parent 467895a9c0
commit 492b337ddd
1 file changed
+42 -1
@@ -10,6 +10,8 @@ import xuan.service.UserInfoService;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -64,7 +66,12 @@ public class UserController {
openId = "guest_" + System.currentTimeMillis();
}
UserInfo user = userInfoService.loginOrRegister(openId, nickname, avatarUrl);
String localAvatarUrl = avatarUrl;
if (avatarUrl != null && !avatarUrl.isEmpty() && avatarUrl.startsWith("http")) {
localAvatarUrl = downloadAvatar(avatarUrl, openId);
}
UserInfo user = userInfoService.loginOrRegister(openId, nickname, localAvatarUrl);
Map<String, Object> data = new HashMap<>();
data.put("id", user.getId());
@@ -88,6 +95,40 @@ public class UserController {
return result;
}
private String downloadAvatar(String imageUrl, String userId) {
try {
String uploadDir = "uploads/avatars/";
File dir = new File(uploadDir);
if (!dir.exists()) {
dir.mkdirs();
}
String extension = ".jpg";
if (imageUrl.contains(".")) {
String tempExt = imageUrl.substring(imageUrl.lastIndexOf("."));
if (tempExt.contains("?")) {
tempExt = tempExt.substring(0, tempExt.indexOf("?"));
}
if (tempExt.length() <= 5 && tempExt.matches("\\.[a-zA-Z]+")) {
extension = tempExt;
}
}
String filename = userId + "_" + System.currentTimeMillis() + extension;
Path filePath = Paths.get(uploadDir + filename);
URL url = new URL(imageUrl);
try (InputStream in = url.openStream()) {
Files.copy(in, filePath);
}
return "/uploads/avatars/" + filename;
} catch (Exception e) {
System.err.println("下载头像失败: " + e.getMessage());
return imageUrl;
}
}
@GetMapping("/info")
public Map<String, Object> getUserInfo(@RequestParam String userId) {
Map<String, Object> result = new HashMap<>();