package com.jiudian.manage.controller; //导入三类核心资源: //自定义业务类:UserService(用户相关业务服务)、FileUtil(文件上传工具类)、State(状态常量类)、StateSignal(统一响应格式工具类); //Spring 注解 / 类:@Autowired(依赖注入)、@RestController(REST 控制器)、@RequestMapping(URL 映射)、@RequestParam(接收请求参数) // 、MultipartFile(Spring 封装的上传文件对象,用于接收前端上传的文件); //Java 标准类:File(文件操作)、FileOutputStream(文件输出流,虽未直接用但工具类可能依赖)、Map(响应数据格式)、UUID(生成唯一文件名)、 // Random(随机数)。 import com.jiudian.manage.service.UserService; import com.jiudian.manage.until.FileUtil; import com.jiudian.manage.until.State; import com.jiudian.manage.until.StateSignal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;//Spring 封装的上传文件对象,用于接收前端上传的文件 import java.io.File; import java.io.FileOutputStream; import java.util.Map; import java.util.Random; import java.util.UUID;//生成唯一文件名 /** * 文件上传控制器 * 主要处理用户头像上传功能 * 流程:前端发起请求,把文件和用户 ID 传给FileController的upFilePhoto.do接口; * FileController调用FileUtil保存文件到服务器,同时调用UserService的photo方法; * UserServiceImpl的photo方法创建User实体,调用UserMapper的updateByPrimaryKeySelective更新数据库; * 最后通过StateSignal封装响应,返回给前端 “成功 / 失败” 的结果。 */ @RestController //标记为REST控制器,返回JSON格式数据 @RequestMapping(value = "/upFile")//定义控制器基础URL路径/根路径,所有方法URL以此为前缀 public class FileController { // 自动注入UserService服务 @Autowired UserService userService; @RequestMapping("/upFilePhoto.do") //返回Map类型(会自动转为 JSON),参数为 “上传文件” 和 “用户 ID”; public Map upFilePhoto(@RequestParam MultipartFile file,@RequestParam int userid){ //接受前端上传文件和用户Id参数 // 生成唯一的文件名,避免文件名冲突 // 使用UUID+原始文件名 String fileName = UUID.randomUUID().toString()+file.getOriginalFilename(); //定义文件保存路径 // 本地保存路径:项目资源目录下的static/File文件夹 String filePath = ".\\src\\main\\resources\\static\\File\\"; // 数据库存储的“相对路径”:前端访问时用该路径 String RealfilePath = "File"+"/"+fileName; // 更新用户头像路径到数据库 boolean photo = userService.photo(userid, RealfilePath); boolean b = false; try { b = FileUtil.uploadFile(file.getBytes(), filePath, fileName); } catch (Exception e) { // 捕获并打印异常信息 e.printStackTrace(); } // 创建状态信号对象,封装 API 接口,用于统一JSON回格式 StateSignal signal = new StateSignal(); if(b&&photo){ signal.put(State.SuccessCode); signal.put(State.SuccessMessage); }else { signal.put(State.ErrorCode); signal.put(State.ErrorMessage); } return signal.getResult(); } }