11package top .whgojp .common .utils ;
22
3- import cn .hutool .core .date .DateUtil ;
43import lombok .extern .slf4j .Slf4j ;
54import org .springframework .beans .factory .annotation .Autowired ;
6- import org .springframework .core .io .ResourceLoader ;
75import org .springframework .stereotype .Component ;
8- import org .springframework .util .StringUtils ;
96import org .springframework .web .multipart .MultipartFile ;
107import top .whgojp .common .constant .SysConstant ;
118
129import java .io .File ;
1310import java .io .IOException ;
14- import java .nio .file .Files ;
15- import java .nio .file .Path ;
16- import java .nio .file .Paths ;
17- import java .util .Objects ;
1811
1912@ Slf4j
2013@ Component
@@ -23,26 +16,26 @@ public class UploadUtil {
2316 @ Autowired
2417 private SysConstant sysConstant ;
2518
26-
27- private static final String UPLOAD_DIR = "uploads" ; // 可以改成配置文件中的路径
28-
29- public String uploadFile (MultipartFile file , String suffix ,String path ) throws IOException {
30-
19+ public String uploadFile (MultipartFile file , String suffix , String path ) throws IOException {
20+ // 从配置中获取上传目录
3121 String uploadFolderPath = sysConstant .getUploadFolder ();
32-
3322 try {
34-
35- String fileName = +DateUtil .current () + "." +suffix ;
36- String newFilePath = uploadFolderPath + "/" + fileName ;
37-
38- file .transferTo (new File (newFilePath )); // 将文件保存到指定路径
23+ // 确保目录存在
24+ File uploadDir = new File (uploadFolderPath );
25+ if (!uploadDir .exists () && !uploadDir .mkdirs ()) {
26+ throw new IOException ("Failed to create upload directory: " + uploadFolderPath );
27+ }
28+ // 构建文件路径
29+ String fileName = System .currentTimeMillis () + "." + suffix ;
30+ String newFilePath = uploadFolderPath + File .separator + fileName ;
31+ // 保存文件
32+ file .transferTo (new File (newFilePath ));
3933 log .info ("上传文件成功,文件路径:" + newFilePath );
4034 return "上传文件成功,文件路径:" + path + fileName ;
4135 } catch (IOException e ) {
42- e .printStackTrace (); // 打印异常堆栈信息
43- log .info ("文件上传失败" + e .getMessage ());
44- return "文件上传失败" + e .getMessage ();
36+ log .error ("文件上传失败:{}" , e .getMessage (), e );
37+ throw e ; // 重新抛出异常供上层处理
4538 }
46-
4739 }
40+
4841}
0 commit comments