diff --git a/src/main/java/com/yeqifu/sys/controller/FileController.java b/src/main/java/com/yeqifu/sys/controller/FileController.java index 849308b..b15564c 100644 --- a/src/main/java/com/yeqifu/sys/controller/FileController.java +++ b/src/main/java/com/yeqifu/sys/controller/FileController.java @@ -19,8 +19,8 @@ import java.util.HashMap; import java.util.Map; /** - * @Author: 落亦- - * @Date: 2019/12/15 23:46 + *@Author zup + *@Date: 2024/12/16 */ @RestController @RequestMapping("file") @@ -33,29 +33,57 @@ public class FileController { */ @RequestMapping("uploadImage") public Map uploadImage(MultipartFile mf) { - // 1. 得到文件名 + Map map = new HashMap<>(); + + // 检查 MultipartFile 是否为空 + if (mf == null || mf.isEmpty()) { + map.put("error", "上传文件为空"); + return map; + } + + // 得到文件名原始名 String oldName = mf.getOriginalFilename(); - // 2. 根据旧的文件名生成新的文件名 - String newName = AppFileUtils.createNewFileName(oldName); - // 3. 得到当前日期的字符串 - String dirName = DateUtil.format(new Date(), "yyyy-MM-dd"); - // 4. 构造文件夹 - File dirFile = new File(AppFileUtils.UPLOAD_PATH, dirName); - // 5. 判断当前文件夹是否存在 - if (!dirFile.exists()) { - // 如果不存在则创建新文件夹 - dirFile.mkdirs(); + + // 检查文件名是否为空 + if (oldName == null || oldName.trim().isEmpty()) { + map.put("error", "文件名为空"); + return map; } - // 6. 构造文件对象 - File file = new File(dirFile, newName + "_temp"); - // 7. 把 mf 里面的图片信息写入 file + try { + // 根据旧的文件名生成新的文件名 + String newName = AppFileUtils.createNewFileName(oldName); + + // 得到当前日期的字符串 + String dirName = DateUtil.format(new Date(), "yyyy-MM-dd"); + + // 构造文件夹 + File dirFile = new File(AppFileUtils.UPLOAD_PATH, dirName); + + // 判断当前文件夹是否存在 + if (!dirFile.exists()) { + // 如果不存在则创建新文件夹 + if (!dirFile.mkdirs()) { + map.put("error", "无法创建上传路径:" + dirFile.getAbsolutePath()); + return map; + } + } + + // 构造文件对象 + File file = new File(dirFile, newName + "_temp"); + + // 把 mf 里面的图片信息写入 file mf.transferTo(file); - } catch (IllegalStateException | IOException e) { + map.put("path", dirName + "/" + newName + "_temp"); + + } catch (IOException e) { + e.printStackTrace(); + map.put("error", "文件上传失败:" + e.getMessage()); + } catch (RuntimeException e) { e.printStackTrace(); + map.put("error", "上传过程发生运行时异常:" + e.getMessage()); } - Map map = new HashMap<>(); - map.put("path", dirName + "/" + newName + "_temp"); + return map; }