FileUtil.java 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package com.lyg.tools.common;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.web.multipart.MultipartFile;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.OutputStream;
  8. import java.time.LocalDateTime;
  9. import java.time.format.DateTimeFormatter;
  10. @Component
  11. public class FileUtil {
  12. @Value("${yz.upload.path}")
  13. String uploadPath;
  14. private void checkUploadPath(String path) throws Exception {
  15. File tmp = new File(path);
  16. if (!tmp.exists()) {
  17. boolean isOk = tmp.mkdirs();
  18. if (!isOk) {
  19. throw new Exception("保存路径创建失败");
  20. }
  21. }
  22. }
  23. private String getMonth() {
  24. LocalDateTime now = LocalDateTime.now();
  25. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
  26. return now.format(formatter);
  27. }
  28. private String[] getFilePaths(String appid, String fileName) throws Exception {
  29. String monthStr = getMonth();
  30. String newFileName = String.format("%d-%s", System.currentTimeMillis(), fileName);
  31. checkUploadPath(String.format("%s/%s/%s", uploadPath, appid, monthStr));
  32. // 绝对路径
  33. String filePath = String.format("%s/%s/%s/%s", uploadPath, appid, monthStr, newFileName);
  34. // 相对路径 - 不包含 uploadPath
  35. String url = String.format("%s/%s/%s", appid, monthStr, newFileName);
  36. return new String[]{filePath, url};
  37. }
  38. // 上传目录
  39. public String saveFile(MultipartFile multipartFile, String appid) throws Exception {
  40. //获取文件名
  41. String fileName = multipartFile.getOriginalFilename();
  42. String[] filePaths = getFilePaths(appid, fileName);
  43. File upFile = new File(filePaths[0]);
  44. multipartFile.transferTo(upFile);
  45. // 返回值 去掉根目录
  46. return filePaths[1];
  47. }
  48. // 保存文件
  49. public String saveFile(File file, String fileName, String appid) throws Exception {
  50. String[] filePaths = getFilePaths(appid, fileName);
  51. if (!file.renameTo(new File(filePaths[0]))) {
  52. throw new Exception("保存文件失败");
  53. }
  54. return filePaths[1];
  55. }
  56. // 保存文件
  57. public String saveFile(byte[] bytes, String fileName, String appid) throws Exception {
  58. String[] filePaths = getFilePaths(appid, fileName);
  59. File file = new File(filePaths[0]);
  60. OutputStream outputStream = new FileOutputStream(file);
  61. outputStream.write(bytes);
  62. outputStream.close();
  63. return filePaths[1];
  64. }
  65. }