FileUtil.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package com.flow.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.web.multipart.MultipartFile;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import java.util.UUID;
  8. public class FileUtil {
  9. private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
  10. public static File upload(MultipartFile file, String filePath) {
  11. // 日期字符串
  12. String format = UUID.randomUUID().toString();
  13. // 文件名称
  14. String fileName = file.getOriginalFilename();
  15. try {
  16. // 路径
  17. String path = String.format("%s%s__%s", filePath, format, fileName);
  18. File dest = new File(path).getCanonicalFile();
  19. // 检测是否存在目录
  20. if (!dest.getParentFile().exists()) {
  21. // 创建目录
  22. if (!dest.getParentFile().mkdirs()) {
  23. log.error("创建目录失败: {}", dest.getParentFile().getPath());
  24. }
  25. }
  26. // 文件写入
  27. file.transferTo(dest);
  28. return dest;
  29. } catch (Exception e) {
  30. log.error(e.getMessage(), e);
  31. }
  32. return null;
  33. }
  34. public static void del(String filePath) {
  35. if (filePath != null && filePath.length() > 0) {
  36. File file = new File(filePath);
  37. if (file.exists()) {
  38. file.delete();
  39. }
  40. }
  41. }
  42. public static String getSuffix(String fileName) {
  43. return fileName.substring(fileName.lastIndexOf("."));
  44. }
  45. }