package com.fzzy.sys.manager.file; import com.fzzy.igds.constant.RespCodeEnum; import com.fzzy.igds.data.PageResponse; import com.fzzy.igds.domain.Dept; import com.fzzy.igds.service.CoreDeptService; import com.fzzy.igds.service.FileService; import com.fzzy.igds.utils.ContextUtil; import com.ruoyi.common.utils.StringUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; /** * @Description 出入库设备相关功能 * @Author CZT * @Date 2025/12/4 9:27 */ @Slf4j @Component("file.fileManager") public class FileManager { @Resource private CoreDeptService coreDeptService; @Resource private FileService fileService; /** * 根据单位ID获取单位信息 * * @param deptId * @return */ public String getDeptFile(String deptId) { if (StringUtils.isEmpty(deptId)) { return null; } String imgBathPath = "未上传"; Dept dept = coreDeptService.getDeptById(deptId); if (StringUtils.isNotEmpty(dept.getImgName())) { File imgFile = new File(dept.getImgName()); if (imgFile.exists()) { imgBathPath = dept.getImgName(); } } return imgBathPath; } /** * 出入库的附件上次,参数是车牌号 * * @param file * @return * @throws IOException */ public PageResponse upLoadInoutHandleImg(MultipartFile file, String plateNum) throws IOException { log.debug("上传出入库的附件……"); // 获取默认编码的字节数组 byte[] fileByte = file.getBytes(); // 获取文件的源文件名称 String oldFileName = file.getOriginalFilename(); // 获取文件保存路径 String filePath = fileService.getFileSavePath("INOUT"); // 获取新的ID String newFileName = ContextUtil.generateId(); // 文件后缀名 String suffixName = oldFileName.substring(oldFileName.lastIndexOf(".")); // 合成新的文件名 if (StringUtils.isEmpty(plateNum)) { newFileName = newFileName + suffixName; } else { newFileName = plateNum + "_" + newFileName + suffixName; } // 文件上传 boolean flag = uploadFile(fileByte, filePath, newFileName); // 判断文件上传是否成功,成功返回文件名 if (flag) { return new PageResponse(RespCodeEnum.CODE_0000.getCode(), newFileName); } else { return new PageResponse(RespCodeEnum.CODE_1111.getCode(), "上传失败"); } } /** * 文件流上传文件 * * @param file * @param filePath * @param fileName * @return */ private static boolean uploadFile(byte[] file, String filePath, String fileName) throws IOException { // 默认文件上传成功 boolean flag = true; // new一个文件对象实例 File targetFile = new File(filePath); // 如果当前文件目录不存在就自动创建该文件或者目录 if (!targetFile.exists()) { targetFile.mkdirs(); } // 创建文件流 FileOutputStream fileOutputStream = new FileOutputStream(filePath + fileName); try { fileOutputStream.write(file); } catch (FileNotFoundException e) { flag = false; } catch (IOException ioException) { flag = false; } finally { fileOutputStream.flush(); fileOutputStream.close(); } return flag; } }