FileUploadUtils.java 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package com.ylx.common.utils.file;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.nio.file.Paths;
  6. import java.util.Objects;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.commons.io.FilenameUtils;
  9. import org.apache.http.entity.ContentType;
  10. import org.springframework.mock.web.MockMultipartFile;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import com.ylx.common.config.RuoYiConfig;
  13. import com.ylx.common.constant.Constants;
  14. import com.ylx.common.exception.file.FileNameLengthLimitExceededException;
  15. import com.ylx.common.exception.file.FileSizeLimitExceededException;
  16. import com.ylx.common.exception.file.InvalidExtensionException;
  17. import com.ylx.common.utils.DateUtils;
  18. import com.ylx.common.utils.StringUtils;
  19. import com.ylx.common.utils.uuid.Seq;
  20. /**
  21. * 文件上传工具类
  22. *
  23. * @author ylx
  24. */
  25. @Slf4j
  26. public class FileUploadUtils {
  27. /**
  28. * 默认大小 50M
  29. */
  30. public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
  31. /**
  32. * 默认的文件名最大长度 100
  33. */
  34. public static final int DEFAULT_FILE_NAME_LENGTH = 100;
  35. /**
  36. * 默认上传的地址
  37. */
  38. private static String defaultBaseDir = RuoYiConfig.getProfile();
  39. public static void setDefaultBaseDir(String defaultBaseDir) {
  40. FileUploadUtils.defaultBaseDir = defaultBaseDir;
  41. }
  42. public static String getDefaultBaseDir() {
  43. return defaultBaseDir;
  44. }
  45. /**
  46. * 以默认配置进行文件上传
  47. *
  48. * @param file 上传的文件
  49. * @return 文件名称
  50. * @throws Exception
  51. */
  52. public static final String upload(MultipartFile file) throws IOException {
  53. try {
  54. return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
  55. } catch (Exception e) {
  56. throw new IOException(e.getMessage(), e);
  57. }
  58. }
  59. /**
  60. * 根据文件路径上传
  61. *
  62. * @param baseDir 相对应用的基目录
  63. * @param file 上传的文件
  64. * @return String 文件名称
  65. * @throws IOException
  66. */
  67. public static final String upload(String baseDir, MultipartFile file) throws IOException {
  68. try {
  69. return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
  70. } catch (Exception e) {
  71. throw new IOException(e.getMessage(), e);
  72. }
  73. }
  74. public static MultipartFile getMultipartFile(File file) {
  75. // String path = "export/demo.xlsx";
  76. // File file = new File(path);
  77. MultipartFile multipartFile;
  78. try {
  79. FileInputStream fileInputStream = new FileInputStream(file);
  80. multipartFile = new MockMultipartFile("copy" + file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
  81. System.out.println(multipartFile.getName()); // 输出demo.xlsx
  82. fileInputStream.close();
  83. } catch (Exception e) {
  84. throw new RuntimeException(e);
  85. }
  86. return multipartFile;
  87. }
  88. /**
  89. * 上传文件
  90. *
  91. * @param baseDir 相对应用的基目录
  92. * @param file 上传的文件
  93. * @param allowedExtension 上传文件类型
  94. * @return 返回上传成功的文件名
  95. * @throws FileSizeLimitExceededException 如果超出最大大小
  96. * @throws FileNameLengthLimitExceededException 文件名太长
  97. * @throws IOException 比如读写文件出错时
  98. * @throws InvalidExtensionException 文件校验异常
  99. */
  100. public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
  101. throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
  102. int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
  103. if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
  104. throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
  105. }
  106. //校验文件大小
  107. assertAllowed(file, allowedExtension);
  108. String fileName = extractFilename(file);
  109. log.info("新的文件名: {}", fileName);
  110. String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
  111. log.info("文件绝对路径: {}", absPath);
  112. file.transferTo(Paths.get(absPath));
  113. return getPathFileName(baseDir, fileName);
  114. }
  115. /**
  116. * 编码文件名
  117. *
  118. * @param file 上传的文件
  119. * @return String 文件名
  120. */
  121. public static final String extractFilename(MultipartFile file) {
  122. return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
  123. FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
  124. }
  125. public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
  126. File desc = new File(uploadDir + File.separator + fileName);
  127. if (!desc.exists()) {
  128. if (!desc.getParentFile().exists()) {
  129. desc.getParentFile().mkdirs();
  130. }
  131. }
  132. return desc;
  133. }
  134. public static final String getPathFileName(String uploadDir, String fileName) throws IOException {
  135. int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
  136. String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
  137. return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
  138. }
  139. /**
  140. * 文件大小校验
  141. *
  142. * @param file 上传的文件
  143. * @param allowedExtension 上传文件类型
  144. * @return
  145. * @throws FileSizeLimitExceededException 如果超出最大大小
  146. * @throws InvalidExtensionException
  147. */
  148. public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
  149. throws FileSizeLimitExceededException, InvalidExtensionException {
  150. long size = file.getSize();
  151. if (size > DEFAULT_MAX_SIZE) {
  152. throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
  153. }
  154. String fileName = file.getOriginalFilename();
  155. String extension = getExtension(file);
  156. if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
  157. // 图片类型
  158. if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
  159. throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, fileName);
  160. } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
  161. throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, fileName);
  162. } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
  163. throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName);
  164. } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
  165. throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension, fileName);
  166. } else {
  167. throw new InvalidExtensionException(allowedExtension, extension, fileName);
  168. }
  169. }
  170. }
  171. /**
  172. * 判断MIME类型是否是允许的MIME类型
  173. *
  174. * @param extension
  175. * @param allowedExtension
  176. * @return
  177. */
  178. public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
  179. for (String str : allowedExtension) {
  180. if (str.equalsIgnoreCase(extension)) {
  181. return true;
  182. }
  183. }
  184. return false;
  185. }
  186. /**
  187. * 获取文件名的后缀
  188. *
  189. * @param file 表单文件
  190. * @return String 后缀名
  191. */
  192. public static final String getExtension(MultipartFile file) {
  193. String extension = FilenameUtils.getExtension(file.getOriginalFilename());
  194. if (StringUtils.isEmpty(extension)) {
  195. extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
  196. }
  197. return extension;
  198. }
  199. }