FileUploadUtils.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package com.xunmei.file.utils;
  2. import cn.hutool.core.codec.Base64;
  3. import cn.hutool.core.io.FileTypeUtil;
  4. import cn.hutool.core.io.FileUtil;
  5. import com.xunmei.common.core.exception.file.FileException;
  6. import com.xunmei.common.core.exception.file.FileNameLengthLimitExceededException;
  7. import com.xunmei.common.core.exception.file.FileSizeLimitExceededException;
  8. import com.xunmei.common.core.exception.file.InvalidExtensionException;
  9. import com.xunmei.common.core.utils.DateUtils;
  10. import com.xunmei.common.core.utils.StringUtils;
  11. import com.xunmei.common.core.utils.file.FileTypeUtils;
  12. import com.xunmei.common.core.utils.file.MimeTypeUtils;
  13. import com.xunmei.common.core.utils.uuid.Seq;
  14. import com.xunmei.file.vo.FileBase64Vo;
  15. import org.apache.commons.io.FileUtils;
  16. import org.apache.commons.lang3.StringEscapeUtils;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.web.multipart.MultipartFile;
  20. import java.io.*;
  21. import java.nio.file.Paths;
  22. import java.util.Objects;
  23. /**
  24. * 文件上传工具类
  25. *
  26. * @author xunmei
  27. */
  28. public class FileUploadUtils
  29. {
  30. private static final Logger log = LoggerFactory.getLogger(FileUploadUtils.class);
  31. /**
  32. * 默认大小 50M
  33. */
  34. public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
  35. /**
  36. * 默认的文件名最大长度 100
  37. */
  38. public static final int DEFAULT_FILE_NAME_LENGTH = 100;
  39. /**
  40. * 根据文件路径上传
  41. *
  42. * @param baseDir 相对应用的基目录
  43. * @param file 上传的文件
  44. * @return 文件名称
  45. * @throws IOException
  46. */
  47. public static final String upload(String baseDir, MultipartFile file) throws IOException
  48. {
  49. try
  50. {
  51. return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION.toArray(new String[0]));
  52. }
  53. catch (FileException fe)
  54. {
  55. throw new IOException(fe.getDefaultMessage(), fe);
  56. }
  57. catch (Exception e)
  58. {
  59. throw new IOException(e.getMessage(), e);
  60. }
  61. }
  62. public static final String upload(String baseDir, MultipartFile file,String busType) throws IOException
  63. {
  64. try
  65. {
  66. String upload = upload(baseDir + File.separator + busType, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION.toArray(new String[0]));
  67. return File.separator + busType + upload;
  68. }
  69. catch (FileException fe)
  70. {
  71. throw new IOException(fe.getDefaultMessage(), fe);
  72. }
  73. catch (Exception e)
  74. {
  75. throw new IOException(e.getMessage(), e);
  76. }
  77. }
  78. /**
  79. * 文件上传
  80. *
  81. * @param baseDir 相对应用的基目录
  82. * @param file 上传的文件
  83. * @param allowedExtension 上传文件类型
  84. * @return 返回上传成功的文件名
  85. * @throws FileSizeLimitExceededException 如果超出最大大小
  86. * @throws FileNameLengthLimitExceededException 文件名太长
  87. * @throws IOException 比如读写文件出错时
  88. * @throws InvalidExtensionException 文件校验异常
  89. */
  90. public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
  91. throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
  92. InvalidExtensionException
  93. {
  94. int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
  95. if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
  96. {
  97. throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
  98. }
  99. assertAllowed(file, allowedExtension);
  100. String fileName = extractFilename(file);
  101. String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
  102. String type = FileTypeUtil.getType(file.getInputStream(),fileName);
  103. File target = FileUtils.getFile(absPath);
  104. file.transferTo(target);
  105. if(!isAllowedExtension(type,allowedExtension)){
  106. FileUtil.del(target);
  107. throw new RuntimeException("上传文件类型不允许");
  108. }
  109. return getPathFileName(fileName);
  110. }
  111. public static final String uploadBase64(String baseDir, FileBase64Vo file)
  112. throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
  113. InvalidExtensionException{
  114. byte[] decode = Base64.decode(file.getContent());
  115. String extension = file.getExtension();
  116. if(StringUtils.isEmpty(extension) || "null".equals(extension))
  117. {
  118. extension="png";
  119. }
  120. String fileName = extractFilename(extension);
  121. File absoluteFile = getAbsoluteFile(baseDir, fileName);
  122. FileUtil.writeBytes(decode,absoluteFile);
  123. return getPathFileName(fileName);
  124. }
  125. /**
  126. * 编码文件名
  127. */
  128. public static final String extractFilename(MultipartFile file)
  129. {
  130. return StringUtils.format("{}/{}.{}", DateUtils.datePath(), Seq.getId(Seq.uploadSeqType), FileTypeUtils.getExtension(file));
  131. }
  132. /**
  133. * 编码文件名
  134. */
  135. public static final String extractFilename(String fileLast)
  136. {
  137. return StringUtils.format("{}/{}.{}", DateUtils.datePath(), Seq.getId(Seq.uploadSeqType), fileLast);
  138. }
  139. public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
  140. {
  141. File desc = FileUtils.getFile(uploadDir,fileName);
  142. //File desc = new File(uploadDir + File.separator + fileName);
  143. String path = StringEscapeUtils.escapeEcmaScript(desc.getAbsolutePath());
  144. String file = StringEscapeUtils.escapeEcmaScript(desc.getParentFile().getName());
  145. log.info("当前上传文件地址:{}",path);
  146. if (!desc.exists())
  147. {
  148. if (!desc.getParentFile().exists())
  149. {
  150. log.info("创建文件夹:{}",file);
  151. desc.getParentFile().mkdirs();
  152. }
  153. }
  154. return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
  155. }
  156. private static final String getPathFileName(String fileName) throws IOException
  157. {
  158. String pathFileName = "/" + fileName;
  159. return pathFileName;
  160. }
  161. /**
  162. * 文件大小校验
  163. *
  164. * @param file 上传的文件
  165. * @throws FileSizeLimitExceededException 如果超出最大大小
  166. * @throws InvalidExtensionException 文件校验异常
  167. */
  168. public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
  169. throws FileSizeLimitExceededException, InvalidExtensionException
  170. {
  171. long size = file.getSize();
  172. if (size > DEFAULT_MAX_SIZE)
  173. {
  174. throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
  175. }
  176. String fileName = file.getOriginalFilename();
  177. String extension = FileTypeUtils.getExtension(file);
  178. if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
  179. {
  180. if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION.toArray(new String[0]))
  181. {
  182. throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
  183. fileName);
  184. }
  185. else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION.toArray(new String[0]))
  186. {
  187. throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
  188. fileName);
  189. }
  190. else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION.toArray(new String[0]))
  191. {
  192. throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
  193. fileName);
  194. }
  195. else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION.toArray(new String[0]))
  196. {
  197. throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
  198. fileName);
  199. }
  200. else
  201. {
  202. throw new InvalidExtensionException(allowedExtension, extension, fileName);
  203. }
  204. }
  205. }
  206. /**
  207. * 判断MIME类型是否是允许的MIME类型
  208. *
  209. * @param extension 上传文件类型
  210. * @param allowedExtension 允许上传文件类型
  211. * @return true/false
  212. */
  213. public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
  214. {
  215. for (String str : allowedExtension)
  216. {
  217. if (str.equalsIgnoreCase(extension))
  218. {
  219. return true;
  220. }
  221. }
  222. return false;
  223. }
  224. }