From faaf907706c62c81c2a91092b950b30c89159afc Mon Sep 17 00:00:00 2001 From: KKSU <15274802129@163.com> Date: Mon, 17 Mar 2025 17:37:52 +0800 Subject: [PATCH] refactor(common): 优化文件上传逻辑 --- src/main/java/cc/mrbird/febs/common/utils/FileUtil.java | 35 +++++++++++++++++++++-------------- 1 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/main/java/cc/mrbird/febs/common/utils/FileUtil.java b/src/main/java/cc/mrbird/febs/common/utils/FileUtil.java index 2e3138d..15d7932 100644 --- a/src/main/java/cc/mrbird/febs/common/utils/FileUtil.java +++ b/src/main/java/cc/mrbird/febs/common/utils/FileUtil.java @@ -7,8 +7,6 @@ import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; @@ -49,6 +47,14 @@ // 获得文件的后缀 String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1); + //限制文件格式为图片 + // 限制文件格式为图片 + if (!isImage(file.getInputStream())) { + Map<String,Object> map = new HashMap<String,Object>(); + map.put("code",1); // 1表示失败 + map.put("msg","文件格式不支持"); // 提示消息 + return map; + } String newFileName = UUID.randomUUID().toString() + "." + fileExt; if (isImage(file.getInputStream())) { Thumbnails.of(file.getInputStream()) @@ -57,19 +63,20 @@ // 图片质量压缩比例 从0-1,越接近1质量越好 .outputQuality(0.9f) .toOutputStream(new FileOutputStream(savePath + newFileName)); - } else { - File uploadedFile = new File(savePath, newFileName); - uploadedFile.setReadable(true, false); - uploadedFile.setExecutable(true, false); - uploadedFile.setWritable(true, false); - try { - //存文件 - FileCopyUtils.copy(file.getBytes(), uploadedFile); - file.transferTo(uploadedFile); - } catch (IOException e) { - e.printStackTrace(); - } } +// else { +// File uploadedFile = new File(savePath, newFileName); +// uploadedFile.setReadable(true, false); +// uploadedFile.setExecutable(true, false); +// uploadedFile.setWritable(true, false); +// try { +// //存文件 +// FileCopyUtils.copy(file.getBytes(), uploadedFile); +// file.transferTo(uploadedFile); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } String visitPath = (saveUrl + newFileName); Map<String,Object> map = new HashMap<String,Object>(); -- Gitblit v1.9.1