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

79 lines
3.4 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;
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;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
//该控制器的主要功能:
//处理用户头像上传请求,路径为/upFile/upFilePhoto.do
//核心流程:
//生成唯一文件名(避免重复)
//定义文件存储路径(本地路径 + 数据库存储的相对路径)
//调用工具类上传文件到本地服务器
//调用用户服务更新数据库中的用户头像路径
//根据上传和数据库更新的结果,返回成功 / 失败的响应状态
// 标记为REST风格控制器所有方法返回数据而非视图
@RestController
// 配置请求路径前缀,所有方法的请求路径都以"/upFile"开头
@RequestMapping(value = "/upFile")
public class FileController {
// 自动注入用户服务类,用于处理用户相关业务(此处主要用于更新用户头像路径)
@Autowired
UserService userService;
// 配置具体请求路径,处理用户头像上传请求
@RequestMapping("/upFilePhoto.do")
// @RequestParam指定请求参数file为上传的文件userid为用户ID
public Map upFilePhoto(@RequestParam MultipartFile file, @RequestParam int userid) {
// 生成唯一文件名UUID避免文件名重复 + 原始文件扩展名(保留文件类型)
String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
// 本地文件存储路径(项目内的静态资源目录)
String filePath = ".\\src\\main\\resources\\static\\File\\";
// 数据库存储的相对路径(用于前端访问时拼接完整路径)
String RealfilePath = "File\\" + fileName;
// 调用用户服务,更新该用户的头像路径到数据库
boolean photo = userService.photo(userid, RealfilePath);
// 标记文件上传是否成功
boolean uploadSuccess = false;
try {
// 调用文件工具类,将文件字节数据上传到指定路径
uploadSuccess = FileUtil.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// 捕获上传过程中的异常并打印堆栈信息
e.printStackTrace();
}
// 创建状态信号对象,用于封装响应结果
StateSignal signal = new StateSignal();
// 判断文件上传和数据库更新是否都成功
if (uploadSuccess && photo) {
// 都成功则返回成功状态码和消息
signal.put(State.SuccessCode);
signal.put(State.SuccessMessage);
} else {
// 有一项失败则返回错误状态码和消息
signal.put(State.ErrorCode);
signal.put(State.ErrorMessage);
}
// 返回封装好的响应结果Map格式
return signal.getResult();
}
}