将文件上传到指定目录,以上传的当天时间新建一个文件夹,以时间戳+UUID的方式对文件进行重命名,防止上传的文件名重复;
pom.xml
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
1 @Value("${uploadPath}") 2 private String uploadPath; 3 4 @PostMapping("/upload") 5 public void upload(MultipartFile filename) throws IOException { 6 // 获取文件原始名称 7 String fileName = filename.getOriginalFilename(); 8 //获取文件后缀 9 String extension = "."+FilenameUtils.getExtension(fileName); 10 //生成新的文件名称 11 String newFileName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-","")+extension; 12 // 根据日期生成目录 13 String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); 14 String dateDirPath = uploadPath + format; 15 File dateDir = new File(dateDirPath); 16 if (!dateDir.exists()) 17 dateDir.mkdirs(); 18 // 处理文件上传 19 filename.transferTo(new File(dateDir, newFileName)); 20 21 }