try {
// 构建日期路径
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/");
String dateUrl = dateFormat.format(currentDate);
// 生成文件名
UUID uuid = UUID.randomUUID();
String originalFileName = file.getOriginalFilename();
assert originalFileName != null;
String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
String fileName = uuid + suffix;
// 创建目录,并保存文件
String savePath = uploadDirectory + dateUrl;
File directory = new File(savePath);
if (!directory.exists()) {
// 如果目录不存在,则创建目录
directory.mkdirs();
}
// 将MultipartFile转换为字节数组
byte[] bytes = file.getBytes();
// 构建文件路径
Path filePath = Paths.get(savePath, fileName);
// 写入文件字节
Files.write(filePath, bytes);
System.out.println(filePath);
// 添加定时任务
timer.schedule(new DeleteFileTask(filePath.toString()), delay);
} catch (IOException e) {
// 这里打个日志吧
throw new RuntimeException(e);
}