You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
test/src/main/java/com/jiudian/manage/controller/FileController.java

74 lines
3.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.jiudian.manage.controller;
//导入三类核心资源:
//自定义业务类UserService用户相关业务服务、FileUtil文件上传工具类、State状态常量类、StateSignal统一响应格式工具类
//Spring 注解 / 类:@Autowired依赖注入、@RestControllerREST 控制器)、@RequestMappingURL 映射)、@RequestParam接收请求参数
// 、MultipartFileSpring 封装的上传文件对象,用于接收前端上传的文件);
//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();
}
}