feat: 添加头像下方修改按钮和头像上传功能
- mine.vue: 头像下方添加灰色修改按钮 - api.js: 添加getBaseUrl方法 - UserController.java: 添加uploadAvatar接口 - WebConfig.java: 配置静态文件服务 - 支持修改用户名和上传头像
This commit is contained in:
1 parent
a10be4ca13
commit
1a48452ccd
4 files changed
+158
-30
No files matched your search
@@ -4,11 +4,18 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import xuan.entity.UserInfo;
|
||||
import xuan.service.UserInfoService;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/user")
|
||||
@@ -319,4 +326,54 @@ public class UserController {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@PostMapping("/uploadAvatar")
|
||||
public Map<String, Object> uploadAvatar(
|
||||
@RequestParam("file") MultipartFile file,
|
||||
@RequestParam("userId") String userId) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (file.isEmpty()) {
|
||||
result.put("success", false);
|
||||
result.put("error", "请选择文件");
|
||||
return result;
|
||||
}
|
||||
|
||||
String uploadDir = "uploads/avatars/";
|
||||
File dir = new File(uploadDir);
|
||||
if (!dir.exists()) {
|
||||
dir.mkdirs();
|
||||
}
|
||||
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String extension = "";
|
||||
if (originalFilename != null && originalFilename.contains(".")) {
|
||||
extension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
}
|
||||
|
||||
String filename = UUID.randomUUID().toString() + extension;
|
||||
Path filePath = Paths.get(uploadDir + filename);
|
||||
Files.write(filePath, file.getBytes());
|
||||
|
||||
String avatarUrl = "/uploads/avatars/" + filename;
|
||||
|
||||
UserInfo user = userInfoService.updateAvatarUrl(userId, avatarUrl);
|
||||
if (user != null) {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("avatarUrl", avatarUrl);
|
||||
result.put("success", true);
|
||||
result.put("data", data);
|
||||
} else {
|
||||
result.put("success", false);
|
||||
result.put("error", "用户不存在");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
result.put("success", false);
|
||||
result.put("error", "文件上传失败: " + e.getMessage());
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("error", e.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user