关于SpringBoot文件上传的记录
- springboot实现文件上传很容易,只需要MultipartFile即可实现。
- 在项目中新建文件夹upload用于保存上传的图片,在数据库中存储对应的图片的位置。
- 保证文件名不重复使用uuid命名。
- 防止文件过多,自定义一个删除文件方法。
//文件上传工具类
public class FileUtils {
public static String saveFile(MultipartFile file) {
File path = null;
try {
path = new File(ResourceUtils.getURL("").getPath() + "/src/main/resources/static/upload/images");
} catch (FileNotFoundException e) {
System.out.println("出错了!找不到指定文件");
return "error";
}
//日期目录
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String datePath = dateFormat.format(new Date());
//最终存放的目录 (contextPath/datePath)
File targetFile = new File(path, datePath);
System.out.println("targetFile=" + targetFile);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
//获取上传文件的完整名称,包括后缀名
String filename = file.getOriginalFilename();
//获取文件后缀名
String fileSuffix = filename.substring(filename.lastIndexOf("."));
//通过uuid随机产生文件名,避免文件名重复导致覆盖
String newFileName = UUID.randomUUID().toString() + fileSuffix;
//最终存放的目录及文件名
File newTargetFile = new File(targetFile, newFileName);
//保存到数据库的路径数据
String savePath = "/upload/images/" + datePath + "/" + newFileName;
try {
file.transferTo(newTargetFile);
return savePath;
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
public static void deleteFile(String filename) {
try {
File file = new File(ResourceUtils.getURL("").getPath() + "/src/main/resources/static/" + filename);
if (!file.isFile()) {
System.out.println("删除失败!找不到指定文件");
return;
}
if (file.delete()) {
System.out.println("删除成功!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@SneakyThrows
public static void main(String[] args) {
String filename = "/upload/images/2022/02/16/457c599c-f83f-403b-99d2-a36c69cd34f6.jpg";
deleteFile(filename);
}
}