springboot:文件上传下载及静态资源访问

川长思鸟来 2024-03-31 16:29 160阅读 0赞

springboot:文件上传下载及静态资源访问

文章目录

  • springboot:文件上传下载及静态资源访问
    • 一、依赖
    • 二、配置类
    • 三、工具类
      • 字符集工具类
      • 类型转换工具类
      • 文件上传工具类
      • 文件处理工具类
      • Md5加密方法
      • 媒体类型工具类
      • 字符串工具类
      • 返回类
    • 四、上传下载功能
      • 上传
      • 下载

完整代码在gitee

一、依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. <scope>test</scope>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.projectlombok</groupId>
  13. <artifactId>lombok</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>cn.hutool</groupId>
  17. <artifactId>hutool-all</artifactId>
  18. <version>5.6.3</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-configuration-processor</artifactId>
  23. <optional>true</optional>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.apache.commons</groupId>
  27. <artifactId>commons-lang3</artifactId>
  28. <version>3.9</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.apache.commons</groupId>
  32. <artifactId>commons-io</artifactId>
  33. <version>1.3.2</version>
  34. </dependency>
  35. </dependencies>

二、配置类

application.properties

  1. server.port=8888
  2. dfs.win.path=D:/myeCode/hlCode/springboot-file/src/main/resources/file-upload
  3. dfs.linux.path=/resources/file-upload
  4. dfs.domain=127.0.0.1:8888

DfsConfig 上传文件信息实体类

  1. @Data
  2. @Component
  3. public class DfsConfig {
  4. /** windows 路径*/
  5. @Value("${dfs.win.path}")
  6. private String winPath;
  7. /** linux或者mac 路径*/
  8. @Value("${dfs.linux.path}")
  9. private String linuxPath;
  10. //生产环境建议用nginx绑定域名映射
  11. /** 域名*/
  12. @Value("${dfs.domain}")
  13. private String domain;
  14. }

自定义静态资源映射配置类

注意:

在这里插入图片描述

  1. package com.example.file.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. /**
  7. * @ClassName ResourcesConfig
  8. * @Description 静态资源映射
  9. * 生产使用为了安全,不建议通过这种方式映射,推荐使用nginx配置
  10. * @Author hl
  11. * @Date 2022/12/8 10:05
  12. * @Version 1.0
  13. */
  14. @Configuration
  15. public class ResourcesConfig implements WebMvcConfigurer {
  16. @Autowired
  17. private DfsConfig dfsConfig;
  18. public static final String RESOURCE_PREFIX = "/profile";
  19. /**
  20. * Spring Boot 访问静态资源的位置(优先级按以下顺序)
  21. * classpath默认就是resources,所以classpath:/static/ 就是resources/static/
  22. * classpath:/META‐INF/resources/
  23. * classpath:/resources/
  24. * classpath:/static/
  25. * classpath:/public/
  26. */
  27. @Override
  28. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  29. String os = System.getProperty("os.name");
  30. if (os.toLowerCase().startsWith("win")) {
  31. //如果是Windows系统
  32. registry.addResourceHandler(RESOURCE_PREFIX + "/**") //指的是对外暴露的访问路径
  33. .addResourceLocations("file:" + dfsConfig.getWinPath()); //指的是内部文件放置的目录
  34. } else {
  35. //linux 和mac
  36. registry.addResourceHandler(RESOURCE_PREFIX + "/**") //指的是对外暴露的访问路径
  37. .addResourceLocations("file:" + dfsConfig.getLinuxPath()); //指的是内部文件放置的目录
  38. }
  39. }
  40. }

三、工具类

字符集工具类

  1. package com.example.file.util;
  2. import org.apache.commons.lang3.StringUtils;
  3. import java.nio.charset.Charset;
  4. import java.nio.charset.StandardCharsets;
  5. /**
  6. * 字符集工具类
  7. */
  8. public class CharsetUtils {
  9. /**
  10. * ISO-8859-1
  11. */
  12. public static final String ISO_8859_1 = "ISO-8859-1";
  13. /**
  14. * UTF-8
  15. */
  16. public static final String UTF_8 = "UTF-8";
  17. /**
  18. * GBK
  19. */
  20. public static final String GBK = "GBK";
  21. /**
  22. * ISO-8859-1
  23. */
  24. public static final Charset CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1;
  25. /**
  26. * UTF-8
  27. */
  28. public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8;
  29. /**
  30. * GBK
  31. */
  32. public static final Charset CHARSET_GBK = Charset.forName(GBK);
  33. /**
  34. * 转换为Charset对象
  35. *
  36. * @param charset 字符集,为空则返回默认字符集
  37. * @return Charset
  38. */
  39. public static Charset charset(String charset) {
  40. return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
  41. }
  42. /**
  43. * 转换字符串的字符集编码
  44. *
  45. * @param source 字符串
  46. * @param srcCharset 源字符集,默认ISO-8859-1
  47. * @param destCharset 目标字符集,默认UTF-8
  48. * @return 转换后的字符集
  49. */
  50. public static String convert(String source, String srcCharset, String destCharset) {
  51. return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
  52. }
  53. /**
  54. * 转换字符串的字符集编码
  55. *
  56. * @param source 字符串
  57. * @param srcCharset 源字符集,默认ISO-8859-1
  58. * @param destCharset 目标字符集,默认UTF-8
  59. * @return 转换后的字符集
  60. */
  61. public static String convert(String source, Charset srcCharset, Charset destCharset) {
  62. if (null == srcCharset) {
  63. srcCharset = StandardCharsets.ISO_8859_1;
  64. }
  65. if (null == destCharset) {
  66. srcCharset = StandardCharsets.UTF_8;
  67. }
  68. if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) {
  69. return source;
  70. }
  71. return new String(source.getBytes(srcCharset), destCharset);
  72. }
  73. /**
  74. * @return 系统字符集编码
  75. */
  76. public static String systemCharset() {
  77. return Charset.defaultCharset().name();
  78. }
  79. }

类型转换工具类

  1. package com.example.file.util;
  2. import org.apache.commons.lang3.StringUtils;
  3. import java.math.BigDecimal;
  4. import java.math.BigInteger;
  5. import java.nio.ByteBuffer;
  6. import java.nio.charset.Charset;
  7. import java.text.NumberFormat;
  8. import java.util.Set;
  9. /**
  10. * 类型转换器
  11. */
  12. public class ConvertUtils {
  13. /**
  14. * 转换为字符串<br>
  15. * 如果给定的值为null,或者转换失败,返回默认值<br>
  16. * 转换失败不会报错
  17. *
  18. * @param value 被转换的值
  19. * @param defaultValue 转换错误时的默认值
  20. * @return 结果
  21. */
  22. public static String toStr(Object value, String defaultValue) {
  23. if (null == value) {
  24. return defaultValue;
  25. }
  26. if (value instanceof String) {
  27. return (String) value;
  28. }
  29. return value.toString();
  30. }
  31. /**
  32. * 转换为字符串<br>
  33. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
  34. * 转换失败不会报错
  35. *
  36. * @param value 被转换的值
  37. * @return 结果
  38. */
  39. public static String toStr(Object value) {
  40. return toStr(value, null);
  41. }
  42. /**
  43. * 转换为字符<br>
  44. * 如果给定的值为null,或者转换失败,返回默认值<br>
  45. * 转换失败不会报错
  46. *
  47. * @param value 被转换的值
  48. * @param defaultValue 转换错误时的默认值
  49. * @return 结果
  50. */
  51. public static Character toChar(Object value, Character defaultValue) {
  52. if (null == value) {
  53. return defaultValue;
  54. }
  55. if (value instanceof Character) {
  56. return (Character) value;
  57. }
  58. final String valueStr = toStr(value, null);
  59. return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);
  60. }
  61. /**
  62. * 转换为字符<br>
  63. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
  64. * 转换失败不会报错
  65. *
  66. * @param value 被转换的值
  67. * @return 结果
  68. */
  69. public static Character toChar(Object value) {
  70. return toChar(value, null);
  71. }
  72. /**
  73. * 转换为byte<br>
  74. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
  75. * 转换失败不会报错
  76. *
  77. * @param value 被转换的值
  78. * @param defaultValue 转换错误时的默认值
  79. * @return 结果
  80. */
  81. public static Byte toByte(Object value, Byte defaultValue) {
  82. if (value == null) {
  83. return defaultValue;
  84. }
  85. if (value instanceof Byte) {
  86. return (Byte) value;
  87. }
  88. if (value instanceof Number) {
  89. return ((Number) value).byteValue();
  90. }
  91. final String valueStr = toStr(value, null);
  92. if (StringUtils.isEmpty(valueStr)) {
  93. return defaultValue;
  94. }
  95. try {
  96. return Byte.parseByte(valueStr);
  97. } catch (Exception e) {
  98. return defaultValue;
  99. }
  100. }
  101. /**
  102. * 转换为byte<br>
  103. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
  104. * 转换失败不会报错
  105. *
  106. * @param value 被转换的值
  107. * @return 结果
  108. */
  109. public static Byte toByte(Object value) {
  110. return toByte(value, null);
  111. }
  112. /**
  113. * 转换为Short<br>
  114. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
  115. * 转换失败不会报错
  116. *
  117. * @param value 被转换的值
  118. * @param defaultValue 转换错误时的默认值
  119. * @return 结果
  120. */
  121. public static Short toShort(Object value, Short defaultValue) {
  122. if (value == null) {
  123. return defaultValue;
  124. }
  125. if (value instanceof Short) {
  126. return (Short) value;
  127. }
  128. if (value instanceof Number) {
  129. return ((Number) value).shortValue();
  130. }
  131. final String valueStr = toStr(value, null);
  132. if (StringUtils.isEmpty(valueStr)) {
  133. return defaultValue;
  134. }
  135. try {
  136. return Short.parseShort(valueStr.trim());
  137. } catch (Exception e) {
  138. return defaultValue;
  139. }
  140. }
  141. /**
  142. * 转换为Short<br>
  143. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
  144. * 转换失败不会报错
  145. *
  146. * @param value 被转换的值
  147. * @return 结果
  148. */
  149. public static Short toShort(Object value) {
  150. return toShort(value, null);
  151. }
  152. /**
  153. * 转换为Number<br>
  154. * 如果给定的值为空,或者转换失败,返回默认值<br>
  155. * 转换失败不会报错
  156. *
  157. * @param value 被转换的值
  158. * @param defaultValue 转换错误时的默认值
  159. * @return 结果
  160. */
  161. public static Number toNumber(Object value, Number defaultValue) {
  162. if (value == null) {
  163. return defaultValue;
  164. }
  165. if (value instanceof Number) {
  166. return (Number) value;
  167. }
  168. final String valueStr = toStr(value, null);
  169. if (StringUtils.isEmpty(valueStr)) {
  170. return defaultValue;
  171. }
  172. try {
  173. return NumberFormat.getInstance().parse(valueStr);
  174. } catch (Exception e) {
  175. return defaultValue;
  176. }
  177. }
  178. /**
  179. * 转换为Number<br>
  180. * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
  181. * 转换失败不会报错
  182. *
  183. * @param value 被转换的值
  184. * @return 结果
  185. */
  186. public static Number toNumber(Object value) {
  187. return toNumber(value, null);
  188. }
  189. /**
  190. * 转换为int<br>
  191. * 如果给定的值为空,或者转换失败,返回默认值<br>
  192. * 转换失败不会报错
  193. *
  194. * @param value 被转换的值
  195. * @param defaultValue 转换错误时的默认值
  196. * @return 结果
  197. */
  198. public static Integer toInt(Object value, Integer defaultValue) {
  199. if (value == null) {
  200. return defaultValue;
  201. }
  202. if (value instanceof Integer) {
  203. return (Integer) value;
  204. }
  205. if (value instanceof Number) {
  206. return ((Number) value).intValue();
  207. }
  208. final String valueStr = toStr(value, null);
  209. if (StringUtils.isEmpty(valueStr)) {
  210. return defaultValue;
  211. }
  212. try {
  213. return Integer.parseInt(valueStr.trim());
  214. } catch (Exception e) {
  215. return defaultValue;
  216. }
  217. }
  218. /**
  219. * 转换为int<br>
  220. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
  221. * 转换失败不会报错
  222. *
  223. * @param value 被转换的值
  224. * @return 结果
  225. */
  226. public static Integer toInt(Object value) {
  227. return toInt(value, null);
  228. }
  229. /**
  230. * 转换为Integer数组<br>
  231. *
  232. * @param str 被转换的值
  233. * @return 结果
  234. */
  235. public static Integer[] toIntArray(String str) {
  236. return toIntArray(",", str);
  237. }
  238. /**
  239. * 转换为Long数组<br>
  240. *
  241. * @param str 被转换的值
  242. * @return 结果
  243. */
  244. public static Long[] toLongArray(String str) {
  245. return toLongArray(",", str);
  246. }
  247. /**
  248. * 转换为Integer数组<br>
  249. *
  250. * @param split 分隔符
  251. * @param split 被转换的值
  252. * @return 结果
  253. */
  254. public static Integer[] toIntArray(String split, String str) {
  255. if (StringUtils.isEmpty(str)) {
  256. return new Integer[]{
  257. };
  258. }
  259. String[] arr = str.split(split);
  260. final Integer[] ints = new Integer[arr.length];
  261. for (int i = 0; i < arr.length; i++) {
  262. final Integer v = toInt(arr[i], 0);
  263. ints[i] = v;
  264. }
  265. return ints;
  266. }
  267. /**
  268. * 转换为Long数组<br>
  269. *
  270. * @param split 分隔符
  271. * @param str 被转换的值
  272. * @return 结果
  273. */
  274. public static Long[] toLongArray(String split, String str) {
  275. if (StringUtils.isEmpty(str)) {
  276. return new Long[]{
  277. };
  278. }
  279. String[] arr = str.split(split);
  280. final Long[] longs = new Long[arr.length];
  281. for (int i = 0; i < arr.length; i++) {
  282. final Long v = toLong(arr[i], null);
  283. longs[i] = v;
  284. }
  285. return longs;
  286. }
  287. /**
  288. * 转换为String数组<br>
  289. *
  290. * @param str 被转换的值
  291. * @return 结果
  292. */
  293. public static String[] toStrArray(String str) {
  294. return toStrArray(",", str);
  295. }
  296. /**
  297. * 转换为String数组<br>
  298. *
  299. * @param split 分隔符
  300. * @param split 被转换的值
  301. * @return 结果
  302. */
  303. public static String[] toStrArray(String split, String str) {
  304. return str.split(split);
  305. }
  306. /**
  307. * 转换为long<br>
  308. * 如果给定的值为空,或者转换失败,返回默认值<br>
  309. * 转换失败不会报错
  310. *
  311. * @param value 被转换的值
  312. * @param defaultValue 转换错误时的默认值
  313. * @return 结果
  314. */
  315. public static Long toLong(Object value, Long defaultValue) {
  316. if (value == null) {
  317. return defaultValue;
  318. }
  319. if (value instanceof Long) {
  320. return (Long) value;
  321. }
  322. if (value instanceof Number) {
  323. return ((Number) value).longValue();
  324. }
  325. final String valueStr = toStr(value, null);
  326. if (StringUtils.isEmpty(valueStr)) {
  327. return defaultValue;
  328. }
  329. try {
  330. // 支持科学计数法
  331. return new BigDecimal(valueStr.trim()).longValue();
  332. } catch (Exception e) {
  333. return defaultValue;
  334. }
  335. }
  336. /**
  337. * 转换为long<br>
  338. * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
  339. * 转换失败不会报错
  340. *
  341. * @param value 被转换的值
  342. * @return 结果
  343. */
  344. public static Long toLong(Object value) {
  345. return toLong(value, null);
  346. }
  347. /**
  348. * 转换为double<br>
  349. * 如果给定的值为空,或者转换失败,返回默认值<br>
  350. * 转换失败不会报错
  351. *
  352. * @param value 被转换的值
  353. * @param defaultValue 转换错误时的默认值
  354. * @return 结果
  355. */
  356. public static Double toDouble(Object value, Double defaultValue) {
  357. if (value == null) {
  358. return defaultValue;
  359. }
  360. if (value instanceof Double) {
  361. return (Double) value;
  362. }
  363. if (value instanceof Number) {
  364. return ((Number) value).doubleValue();
  365. }
  366. final String valueStr = toStr(value, null);
  367. if (StringUtils.isEmpty(valueStr)) {
  368. return defaultValue;
  369. }
  370. try {
  371. // 支持科学计数法
  372. return new BigDecimal(valueStr.trim()).doubleValue();
  373. } catch (Exception e) {
  374. return defaultValue;
  375. }
  376. }
  377. /**
  378. * 转换为double<br>
  379. * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
  380. * 转换失败不会报错
  381. *
  382. * @param value 被转换的值
  383. * @return 结果
  384. */
  385. public static Double toDouble(Object value) {
  386. return toDouble(value, null);
  387. }
  388. /**
  389. * 转换为Float<br>
  390. * 如果给定的值为空,或者转换失败,返回默认值<br>
  391. * 转换失败不会报错
  392. *
  393. * @param value 被转换的值
  394. * @param defaultValue 转换错误时的默认值
  395. * @return 结果
  396. */
  397. public static Float toFloat(Object value, Float defaultValue) {
  398. if (value == null) {
  399. return defaultValue;
  400. }
  401. if (value instanceof Float) {
  402. return (Float) value;
  403. }
  404. if (value instanceof Number) {
  405. return ((Number) value).floatValue();
  406. }
  407. final String valueStr = toStr(value, null);
  408. if (StringUtils.isEmpty(valueStr)) {
  409. return defaultValue;
  410. }
  411. try {
  412. return Float.parseFloat(valueStr.trim());
  413. } catch (Exception e) {
  414. return defaultValue;
  415. }
  416. }
  417. /**
  418. * 转换为Float<br>
  419. * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
  420. * 转换失败不会报错
  421. *
  422. * @param value 被转换的值
  423. * @return 结果
  424. */
  425. public static Float toFloat(Object value) {
  426. return toFloat(value, null);
  427. }
  428. /**
  429. * 转换为boolean<br>
  430. * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值<br>
  431. * 转换失败不会报错
  432. *
  433. * @param value 被转换的值
  434. * @param defaultValue 转换错误时的默认值
  435. * @return 结果
  436. */
  437. public static Boolean toBool(Object value, Boolean defaultValue) {
  438. if (value == null) {
  439. return defaultValue;
  440. }
  441. if (value instanceof Boolean) {
  442. return (Boolean) value;
  443. }
  444. String valueStr = toStr(value, null);
  445. if (StringUtils.isEmpty(valueStr)) {
  446. return defaultValue;
  447. }
  448. valueStr = valueStr.trim().toLowerCase();
  449. switch (valueStr) {
  450. case "true":
  451. return true;
  452. case "false":
  453. return false;
  454. case "yes":
  455. return true;
  456. case "ok":
  457. return true;
  458. case "no":
  459. return false;
  460. case "1":
  461. return true;
  462. case "0":
  463. return false;
  464. default:
  465. return defaultValue;
  466. }
  467. }
  468. /**
  469. * 转换为boolean<br>
  470. * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
  471. * 转换失败不会报错
  472. *
  473. * @param value 被转换的值
  474. * @return 结果
  475. */
  476. public static Boolean toBool(Object value) {
  477. return toBool(value, null);
  478. }
  479. /**
  480. * 转换为Enum对象<br>
  481. * 如果给定的值为空,或者转换失败,返回默认值<br>
  482. *
  483. * @param clazz Enum的Class
  484. * @param value 值
  485. * @param defaultValue 默认值
  486. * @return Enum
  487. */
  488. public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue) {
  489. if (value == null) {
  490. return defaultValue;
  491. }
  492. if (clazz.isAssignableFrom(value.getClass())) {
  493. @SuppressWarnings("unchecked")
  494. E myE = (E) value;
  495. return myE;
  496. }
  497. final String valueStr = toStr(value, null);
  498. if (StringUtils.isEmpty(valueStr)) {
  499. return defaultValue;
  500. }
  501. try {
  502. return Enum.valueOf(clazz, valueStr);
  503. } catch (Exception e) {
  504. return defaultValue;
  505. }
  506. }
  507. /**
  508. * 转换为Enum对象<br>
  509. * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
  510. *
  511. * @param clazz Enum的Class
  512. * @param value 值
  513. * @return Enum
  514. */
  515. public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value) {
  516. return toEnum(clazz, value, null);
  517. }
  518. /**
  519. * 转换为BigInteger<br>
  520. * 如果给定的值为空,或者转换失败,返回默认值<br>
  521. * 转换失败不会报错
  522. *
  523. * @param value 被转换的值
  524. * @param defaultValue 转换错误时的默认值
  525. * @return 结果
  526. */
  527. public static BigInteger toBigInteger(Object value, BigInteger defaultValue) {
  528. if (value == null) {
  529. return defaultValue;
  530. }
  531. if (value instanceof BigInteger) {
  532. return (BigInteger) value;
  533. }
  534. if (value instanceof Long) {
  535. return BigInteger.valueOf((Long) value);
  536. }
  537. final String valueStr = toStr(value, null);
  538. if (StringUtils.isEmpty(valueStr)) {
  539. return defaultValue;
  540. }
  541. try {
  542. return new BigInteger(valueStr);
  543. } catch (Exception e) {
  544. return defaultValue;
  545. }
  546. }
  547. /**
  548. * 转换为BigInteger<br>
  549. * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
  550. * 转换失败不会报错
  551. *
  552. * @param value 被转换的值
  553. * @return 结果
  554. */
  555. public static BigInteger toBigInteger(Object value) {
  556. return toBigInteger(value, null);
  557. }
  558. /**
  559. * 转换为BigDecimal<br>
  560. * 如果给定的值为空,或者转换失败,返回默认值<br>
  561. * 转换失败不会报错
  562. *
  563. * @param value 被转换的值
  564. * @param defaultValue 转换错误时的默认值
  565. * @return 结果
  566. */
  567. public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) {
  568. if (value == null) {
  569. return defaultValue;
  570. }
  571. if (value instanceof BigDecimal) {
  572. return (BigDecimal) value;
  573. }
  574. if (value instanceof Long) {
  575. return new BigDecimal((Long) value);
  576. }
  577. if (value instanceof Double) {
  578. return BigDecimal.valueOf((Double) value);
  579. }
  580. if (value instanceof Integer) {
  581. return new BigDecimal((Integer) value);
  582. }
  583. final String valueStr = toStr(value, null);
  584. if (StringUtils.isEmpty(valueStr)) {
  585. return defaultValue;
  586. }
  587. try {
  588. return new BigDecimal(valueStr);
  589. } catch (Exception e) {
  590. return defaultValue;
  591. }
  592. }
  593. /**
  594. * 转换为BigDecimal<br>
  595. * 如果给定的值为空,或者转换失败,返回默认值<br>
  596. * 转换失败不会报错
  597. *
  598. * @param value 被转换的值
  599. * @return 结果
  600. */
  601. public static BigDecimal toBigDecimal(Object value) {
  602. return toBigDecimal(value, null);
  603. }
  604. /**
  605. * 将对象转为字符串<br>
  606. * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
  607. *
  608. * @param obj 对象
  609. * @return 字符串
  610. */
  611. public static String utf8Str(Object obj) {
  612. return str(obj, CharsetUtils.CHARSET_UTF_8);
  613. }
  614. /**
  615. * 将对象转为字符串<br>
  616. * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
  617. *
  618. * @param obj 对象
  619. * @param charsetName 字符集
  620. * @return 字符串
  621. */
  622. public static String str(Object obj, String charsetName) {
  623. return str(obj, Charset.forName(charsetName));
  624. }
  625. /**
  626. * 将对象转为字符串<br>
  627. * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
  628. *
  629. * @param obj 对象
  630. * @param charset 字符集
  631. * @return 字符串
  632. */
  633. public static String str(Object obj, Charset charset) {
  634. if (null == obj) {
  635. return null;
  636. }
  637. if (obj instanceof String) {
  638. return (String) obj;
  639. } else if (obj instanceof byte[] || obj instanceof Byte[]) {
  640. return str((Byte[]) obj, charset);
  641. } else if (obj instanceof ByteBuffer) {
  642. return str((ByteBuffer) obj, charset);
  643. }
  644. return obj.toString();
  645. }
  646. /**
  647. * 将byte数组转为字符串
  648. *
  649. * @param bytes byte数组
  650. * @param charset 字符集
  651. * @return 字符串
  652. */
  653. public static String str(byte[] bytes, String charset) {
  654. return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));
  655. }
  656. /**
  657. * 解码字节码
  658. *
  659. * @param data 字符串
  660. * @param charset 字符集,如果此字段为空,则解码的结果取决于平台
  661. * @return 解码后的字符串
  662. */
  663. public static String str(byte[] data, Charset charset) {
  664. if (data == null) {
  665. return null;
  666. }
  667. if (null == charset) {
  668. return new String(data);
  669. }
  670. return new String(data, charset);
  671. }
  672. /**
  673. * 将编码的byteBuffer数据转换为字符串
  674. *
  675. * @param data 数据
  676. * @param charset 字符集,如果为空使用当前系统字符集
  677. * @return 字符串
  678. */
  679. public static String str(ByteBuffer data, String charset) {
  680. if (data == null) {
  681. return null;
  682. }
  683. return str(data, Charset.forName(charset));
  684. }
  685. /**
  686. * 将编码的byteBuffer数据转换为字符串
  687. *
  688. * @param data 数据
  689. * @param charset 字符集,如果为空使用当前系统字符集
  690. * @return 字符串
  691. */
  692. public static String str(ByteBuffer data, Charset charset) {
  693. if (null == charset) {
  694. charset = Charset.defaultCharset();
  695. }
  696. return charset.decode(data).toString();
  697. }
  698. // ----------------------------------------------------------------------- 全角半角转换
  699. /**
  700. * 半角转全角
  701. *
  702. * @param input String.
  703. * @return 全角字符串.
  704. */
  705. public static String toSBC(String input) {
  706. return toSBC(input, null);
  707. }
  708. /**
  709. * 半角转全角
  710. *
  711. * @param input String
  712. * @param notConvertSet 不替换的字符集合
  713. * @return 全角字符串.
  714. */
  715. public static String toSBC(String input, Set<Character> notConvertSet) {
  716. char c[] = input.toCharArray();
  717. for (int i = 0; i < c.length; i++) {
  718. if (null != notConvertSet && notConvertSet.contains(c[i])) {
  719. // 跳过不替换的字符
  720. continue;
  721. }
  722. if (c[i] == ' ') {
  723. c[i] = '\u3000';
  724. } else if (c[i] < '\177') {
  725. c[i] = (char) (c[i] + 65248);
  726. }
  727. }
  728. return new String(c);
  729. }
  730. /**
  731. * 全角转半角
  732. *
  733. * @param input String.
  734. * @return 半角字符串
  735. */
  736. public static String toDBC(String input) {
  737. return toDBC(input, null);
  738. }
  739. /**
  740. * 替换全角为半角
  741. *
  742. * @param text 文本
  743. * @param notConvertSet 不替换的字符集合
  744. * @return 替换后的字符
  745. */
  746. public static String toDBC(String text, Set<Character> notConvertSet) {
  747. char c[] = text.toCharArray();
  748. for (int i = 0; i < c.length; i++) {
  749. if (null != notConvertSet && notConvertSet.contains(c[i])) {
  750. // 跳过不替换的字符
  751. continue;
  752. }
  753. if (c[i] == '\u3000') {
  754. c[i] = ' ';
  755. } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
  756. c[i] = (char) (c[i] - 65248);
  757. }
  758. }
  759. return new String(c);
  760. }
  761. /**
  762. * 数字金额大写转换 先写个完整的然后将如零拾替换成零
  763. *
  764. * @param n 数字
  765. * @return 中文大写数字
  766. */
  767. public static String digitUppercase(double n) {
  768. String[] fraction = {
  769. "角", "分"};
  770. String[] digit = {
  771. "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
  772. String[][] unit = {
  773. {
  774. "元", "万", "亿"}, {
  775. "", "拾", "佰", "仟"}};
  776. String head = n < 0 ? "负" : "";
  777. n = Math.abs(n);
  778. StringBuilder s = new StringBuilder();
  779. for (int i = 0; i < fraction.length; i++) {
  780. s.append((digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""));
  781. }
  782. if (s.length() < 1) {
  783. s = new StringBuilder("整");
  784. }
  785. int integerPart = (int) Math.floor(n);
  786. for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
  787. String p = "";
  788. for (int j = 0; j < unit[1].length && n > 0; j++) {
  789. p = digit[integerPart % 10] + unit[1][j] + p;
  790. integerPart = integerPart / 10;
  791. }
  792. s.insert(0, p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i]);
  793. }
  794. return head + s.toString().replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
  795. }
  796. }

文件上传工具类

  1. package com.example.file.util;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.Arrays;
  5. import java.util.Date;
  6. import java.util.Objects;
  7. import org.apache.commons.io.FilenameUtils;
  8. import org.apache.commons.lang3.time.DateFormatUtils;
  9. import org.apache.tomcat.util.http.fileupload.FileUploadException;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import javax.annotation.processing.FilerException;
  12. /**
  13. * 文件上传工具类
  14. *
  15. * @author ruoyi
  16. */
  17. public class FileUploadUtils {
  18. /**
  19. * 默认大小 50M
  20. */
  21. public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
  22. /**
  23. * 默认的文件名最大长度 100
  24. */
  25. public static final int DEFAULT_FILE_NAME_LENGTH = 100;
  26. private static int counter = 0;
  27. public static final String RESOURCE_PREFIX = "/profile";
  28. /**
  29. * 根据文件路径上传
  30. *
  31. * @param baseDir 相对应用的基目录
  32. * @param file 上传的文件
  33. * @return 文件名称
  34. * @throws IOException
  35. */
  36. public static String upload(String baseDir, MultipartFile file) throws IOException {
  37. try {
  38. return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
  39. } catch (Exception e) {
  40. throw new IOException(e.getMessage(), e);
  41. }
  42. }
  43. /**
  44. * 文件上传
  45. *
  46. * @param baseDir 相对应用的基目录
  47. * @param file 上传的文件
  48. * @param allowedExtension 上传文件类型
  49. * @return 返回上传成功的文件名
  50. * @throws IOException 比如读写文件出错时
  51. */
  52. public static String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws IOException, FileUploadException {
  53. int fileNameLength = Objects.requireNonNull(file.getOriginalFilename()).length();
  54. if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
  55. throw new FilerException("默认的文件名最大长度 :" + DEFAULT_FILE_NAME_LENGTH);
  56. }
  57. assertAllowed(file, allowedExtension);
  58. String fileName = extractFilename(file);
  59. File desc = new File(baseDir + File.separator + fileName);
  60. if (!desc.getParentFile().exists()){
  61. desc.getParentFile().mkdirs();
  62. }
  63. file.transferTo(desc);
  64. return getPathFileName(baseDir, fileName);
  65. }
  66. /**
  67. * 编码文件名
  68. */
  69. public static String extractFilename(MultipartFile file) {
  70. String fileName = file.getOriginalFilename();
  71. String extension = getExtension(file);
  72. fileName = datePath() + "/" + encodingFilename(fileName) + "." + extension;
  73. return fileName;
  74. }
  75. public static String datePath() {
  76. Date now = new Date();
  77. return DateFormatUtils.format(now, "yyyy/MM/dd");
  78. }
  79. private static String getPathFileName(String uploadDir, String fileName){
  80. int dirLastIndex = uploadDir.lastIndexOf("/") + 1;
  81. String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
  82. return RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
  83. }
  84. /**
  85. * 编码文件名
  86. */
  87. private static String encodingFilename(String fileName) {
  88. return Md5Utils.hash(fileName.replace("_", " ") + System.nanoTime() + counter++);
  89. }
  90. /**
  91. * 文件大小校验
  92. *
  93. * @param file 上传的文件
  94. */
  95. public static void assertAllowed(MultipartFile file, String[] allowedExtension) throws FilerException, FileUploadException {
  96. long size = file.getSize();
  97. if (size > DEFAULT_MAX_SIZE) {
  98. throw new FilerException("默认的文件名最大长度 :" + DEFAULT_MAX_SIZE / 1024 / 1024);
  99. }
  100. String fileName = file.getOriginalFilename();
  101. String extension = getExtension(file);
  102. if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
  103. if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
  104. throw new FileUploadException("filename : [" + fileName + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
  105. } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
  106. throw new FileUploadException("filename : [" + fileName + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
  107. } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
  108. throw new FileUploadException("filename : [" + fileName + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
  109. } else {
  110. throw new FileUploadException("filename : [" + fileName + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
  111. }
  112. }
  113. }
  114. /**
  115. * 判断MIME类型是否是允许的MIME类型
  116. *
  117. * @param extension
  118. * @param allowedExtension
  119. * @return
  120. */
  121. public static boolean isAllowedExtension(String extension, String[] allowedExtension) {
  122. for (String str : allowedExtension) {
  123. if (str.equalsIgnoreCase(extension)) {
  124. return true;
  125. }
  126. }
  127. return false;
  128. }
  129. /**
  130. * 获取文件名的后缀
  131. *
  132. * @param file 表单文件
  133. * @return 后缀名
  134. */
  135. public static String getExtension(MultipartFile file) {
  136. String extension = FilenameUtils.getExtension(file.getOriginalFilename());
  137. if (StringUtils.isEmpty(extension)) {
  138. extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
  139. }
  140. return extension;
  141. }
  142. }

文件处理工具类

  1. package com.example.file.util;
  2. import javax.servlet.http.HttpServletRequest;
  3. import java.io.*;
  4. import java.net.URLEncoder;
  5. /**
  6. * 文件处理工具类
  7. */
  8. public class FileUtils {
  9. public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\/\\u4e00-\\u9fa5]+";
  10. /**
  11. * 输出指定文件的byte数组
  12. *
  13. * @param filePath 文件路径
  14. * @param os 输出流
  15. */
  16. public static void writeBytes(String filePath, OutputStream os) throws IOException {
  17. FileInputStream fis = null;
  18. try {
  19. File file = new File(filePath);
  20. if (!file.exists()) {
  21. throw new FileNotFoundException(filePath);
  22. }
  23. fis = new FileInputStream(file);
  24. byte[] b = new byte[1024];
  25. int length;
  26. while ((length = fis.read(b)) > 0) {
  27. os.write(b, 0, length);
  28. }
  29. } finally {
  30. if (os != null) {
  31. try {
  32. os.close();
  33. } catch (IOException e1) {
  34. e1.printStackTrace();
  35. }
  36. }
  37. if (fis != null) {
  38. try {
  39. fis.close();
  40. } catch (IOException e1) {
  41. e1.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  46. /**
  47. * 删除文件
  48. *
  49. * @param filePath 文件
  50. */
  51. public static void deleteFile(String filePath) {
  52. File file = new File(filePath);
  53. // 路径为文件且不为空则进行删除
  54. if (file.isFile() && file.exists()) {
  55. file.delete();
  56. }
  57. }
  58. /**
  59. * 文件名称验证
  60. *
  61. * @param filename 文件名称
  62. * @return true 正常 false 非法
  63. */
  64. public static boolean isValidFilename(String filename) {
  65. return filename.matches(FILENAME_PATTERN);
  66. }
  67. /**
  68. * 下载文件名重新编码
  69. *
  70. * @param request 请求对象
  71. * @param fileName 文件名
  72. * @return 编码后的文件名
  73. */
  74. public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
  75. throws UnsupportedEncodingException {
  76. final String agent = request.getHeader("USER-AGENT");
  77. String filename = fileName;
  78. if (agent.contains("MSIE")) {
  79. // IE浏览器
  80. filename = URLEncoder.encode(filename, "utf-8");
  81. filename = filename.replace("+", " ");
  82. } else if (agent.contains("Firefox")) {
  83. // 火狐浏览器
  84. filename = new String(fileName.getBytes(), "ISO8859-1");
  85. } else if (agent.contains("Chrome")) {
  86. // google浏览器
  87. filename = URLEncoder.encode(filename, "utf-8");
  88. } else {
  89. // 其它浏览器
  90. filename = URLEncoder.encode(filename, "utf-8");
  91. }
  92. return filename;
  93. }
  94. /**
  95. * 获取系统临时目录
  96. *
  97. */
  98. public static String getTemp() {
  99. return System.getProperty("java.io.tmpdir");
  100. }
  101. /**
  102. * 创建临时文件
  103. *
  104. * @param filePath
  105. * @param data
  106. */
  107. public static File createTempFile(String filePath, byte[] data) throws IOException {
  108. String temp = getTemp() + filePath;
  109. File file = new File(temp);
  110. if (!file.getParentFile().exists()) {
  111. file.getParentFile().mkdirs();
  112. }
  113. if (!file.exists()) {
  114. file.createNewFile();
  115. }
  116. FileOutputStream fos = new FileOutputStream(file);
  117. fos.write(data, 0, data.length);
  118. fos.flush();
  119. fos.close();
  120. return file;
  121. }
  122. }

Md5加密方法

  1. package com.example.file.util;
  2. import java.nio.charset.StandardCharsets;
  3. import java.security.MessageDigest;
  4. import java.util.Objects;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. /**
  8. * Md5加密方法
  9. */
  10. public class Md5Utils {
  11. private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
  12. private static byte[] md5(String s) {
  13. MessageDigest algorithm;
  14. try {
  15. algorithm = MessageDigest.getInstance("MD5");
  16. algorithm.reset();
  17. algorithm.update(s.getBytes(StandardCharsets.UTF_8));
  18. return algorithm.digest();
  19. } catch (Exception e) {
  20. log.error("MD5 Error...", e);
  21. }
  22. return null;
  23. }
  24. private static String toHex(byte[] hash) {
  25. if (hash == null) {
  26. return null;
  27. }
  28. StringBuilder buf = new StringBuilder(hash.length * 2);
  29. int i;
  30. for (i = 0; i < hash.length; i++) {
  31. if ((hash[i] & 0xff) < 0x10) {
  32. buf.append("0");
  33. }
  34. buf.append(Long.toString(hash[i] & 0xff, 16));
  35. }
  36. return buf.toString();
  37. }
  38. public static String hash(String s) {
  39. try {
  40. return new String(Objects.requireNonNull(toHex(md5(s))).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
  41. } catch (Exception e) {
  42. log.error("not supported charset...{}", e);
  43. return s;
  44. }
  45. }
  46. }

媒体类型工具类

  1. package com.example.file.util;
  2. /**
  3. * 媒体类型工具类
  4. */
  5. public class MimeTypeUtils {
  6. public static final String IMAGE_PNG = "image/png";
  7. public static final String IMAGE_JPG = "image/jpg";
  8. public static final String IMAGE_JPEG = "image/jpeg";
  9. public static final String IMAGE_BMP = "image/bmp";
  10. public static final String IMAGE_GIF = "image/gif";
  11. public static final String[] IMAGE_EXTENSION = {
  12. "bmp", "gif", "jpg", "jpeg", "png"};
  13. public static final String[] FLASH_EXTENSION = {
  14. "swf", "flv"};
  15. public static final String[] MEDIA_EXTENSION = {
  16. "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
  17. "asf", "rm", "rmvb"};
  18. public static final String[] DEFAULT_ALLOWED_EXTENSION = {
  19. // 图片
  20. "bmp", "gif", "jpg", "jpeg", "png",
  21. // word excel powerpoint
  22. "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
  23. // 压缩文件
  24. "rar", "zip", "gz", "bz2",
  25. // pdf
  26. "pdf"};
  27. public static String getExtension(String prefix) {
  28. switch (prefix) {
  29. case IMAGE_PNG:
  30. return "png";
  31. case IMAGE_JPG:
  32. return "jpg";
  33. case IMAGE_JPEG:
  34. return "jpeg";
  35. case IMAGE_BMP:
  36. return "bmp";
  37. case IMAGE_GIF:
  38. return "gif";
  39. default:
  40. return "";
  41. }
  42. }
  43. }

字符串工具类

  1. package com.example.file.util;
  2. import java.util.Collection;
  3. import java.util.Map;
  4. /**
  5. * 字符串工具类
  6. */
  7. public class StringUtils extends org.apache.commons.lang3.StringUtils {
  8. /**
  9. * 空字符串
  10. */
  11. private static final String NULLSTR = "";
  12. /**
  13. * 下划线
  14. */
  15. private static final char SEPARATOR = '_';
  16. private static final String EMPTY_JSON = "{}";
  17. private static final char C_BACKSLASH = '\\';
  18. private static final char C_DELIM_START = '{';
  19. /**
  20. * 获取参数不为空值
  21. *
  22. * @param value defaultValue 要判断的value
  23. * @return value 返回值
  24. */
  25. public static <T> T nvl(T value, T defaultValue) {
  26. return value != null ? value : defaultValue;
  27. }
  28. /**
  29. * * 判断一个Collection是否为空, 包含List,Set,Queue
  30. *
  31. * @param coll 要判断的Collection
  32. * @return true:为空 false:非空
  33. */
  34. public static boolean isEmpty(Collection<?> coll) {
  35. return isNull(coll) || coll.isEmpty();
  36. }
  37. /**
  38. * * 判断一个Collection是否非空,包含List,Set,Queue
  39. *
  40. * @param coll 要判断的Collection
  41. * @return true:非空 false:空
  42. */
  43. public static boolean isNotEmpty(Collection<?> coll) {
  44. return !isEmpty(coll);
  45. }
  46. /**
  47. * * 判断一个对象数组是否为空
  48. *
  49. * @param objects 要判断的对象数组
  50. * * @return true:为空 false:非空
  51. */
  52. public static boolean isEmpty(Object[] objects) {
  53. return isNull(objects) || (objects.length == 0);
  54. }
  55. /**
  56. * * 判断一个对象数组是否非空
  57. *
  58. * @param objects 要判断的对象数组
  59. * @return true:非空 false:空
  60. */
  61. public static boolean isNotEmpty(Object[] objects) {
  62. return !isEmpty(objects);
  63. }
  64. /**
  65. * * 判断一个Map是否为空
  66. *
  67. * @param map 要判断的Map
  68. * @return true:为空 false:非空
  69. */
  70. public static boolean isEmpty(Map<?, ?> map) {
  71. return isNull(map) || map.isEmpty();
  72. }
  73. /**
  74. * * 判断一个Map是否为空
  75. *
  76. * @param map 要判断的Map
  77. * @return true:非空 false:空
  78. */
  79. public static boolean isNotEmpty(Map<?, ?> map) {
  80. return !isEmpty(map);
  81. }
  82. /**
  83. * * 判断一个字符串是否为空串
  84. *
  85. * @param str String
  86. * @return true:为空 false:非空
  87. */
  88. public static boolean isEmpty(String str) {
  89. return isNull(str) || NULLSTR.equals(str.trim());
  90. }
  91. /**
  92. * * 判断一个字符串是否为非空串
  93. *
  94. * @param str String
  95. * @return true:非空串 false:空串
  96. */
  97. public static boolean isNotEmpty(String str) {
  98. return !isEmpty(str);
  99. }
  100. /**
  101. * * 判断一个对象是否为空
  102. *
  103. * @param object Object
  104. * @return true:为空 false:非空
  105. */
  106. public static boolean isNull(Object object) {
  107. return object == null;
  108. }
  109. /**
  110. * * 判断一个对象是否非空
  111. *
  112. * @param object Object
  113. * @return true:非空 false:空
  114. */
  115. public static boolean isNotNull(Object object) {
  116. return !isNull(object);
  117. }
  118. /**
  119. * * 判断一个对象是否是数组类型(Java基本型别的数组)
  120. *
  121. * @param object 对象
  122. * @return true:是数组 false:不是数组
  123. */
  124. public static boolean isArray(Object object) {
  125. return isNotNull(object) && object.getClass().isArray();
  126. }
  127. /**
  128. * 去空格
  129. */
  130. public static String trim(String str) {
  131. return (str == null ? "" : str.trim());
  132. }
  133. /**
  134. * 截取字符串
  135. *
  136. * @param str 字符串
  137. * @param start 开始
  138. * @return 结果
  139. */
  140. public static String substring(final String str, int start) {
  141. if (str == null) {
  142. return NULLSTR;
  143. }
  144. if (start < 0) {
  145. start = str.length() + start;
  146. }
  147. if (start < 0) {
  148. start = 0;
  149. }
  150. if (start > str.length()) {
  151. return NULLSTR;
  152. }
  153. return str.substring(start);
  154. }
  155. /**
  156. * 截取字符串
  157. *
  158. * @param str 字符串
  159. * @param start 开始
  160. * @param end 结束
  161. * @return 结果
  162. */
  163. public static String substring(final String str, int start, int end) {
  164. if (str == null) {
  165. return NULLSTR;
  166. }
  167. if (end < 0) {
  168. end = str.length() + end;
  169. }
  170. if (start < 0) {
  171. start = str.length() + start;
  172. }
  173. if (end > str.length()) {
  174. end = str.length();
  175. }
  176. if (start > end) {
  177. return NULLSTR;
  178. }
  179. if (start < 0) {
  180. start = 0;
  181. }
  182. if (end < 0) {
  183. end = 0;
  184. }
  185. return str.substring(start, end);
  186. }
  187. /**
  188. * 格式化字符串<br>
  189. * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
  190. * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
  191. * 例:<br>
  192. * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
  193. * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
  194. * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
  195. *
  196. * @param strPattern 字符串模板
  197. * @param argArray 参数列表
  198. * @return 结果
  199. */
  200. public static String strFormat(String strPattern, Object... argArray) {
  201. if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) {
  202. return strPattern;
  203. }
  204. final int strPatternLength = strPattern.length();
  205. // 初始化定义好的长度以获得更好的性能
  206. StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
  207. int handledPosition = 0;
  208. int delimIndex;// 占位符所在位置
  209. for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
  210. delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
  211. if (delimIndex == -1) {
  212. if (handledPosition == 0) {
  213. return strPattern;
  214. } else {
  215. // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
  216. sbuf.append(strPattern, handledPosition, strPatternLength);
  217. return sbuf.toString();
  218. }
  219. } else {
  220. if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) {
  221. if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) {
  222. // 转义符之前还有一个转义符,占位符依旧有效
  223. sbuf.append(strPattern, handledPosition, delimIndex - 1);
  224. sbuf.append(ConvertUtils.utf8Str(argArray[argIndex]));
  225. handledPosition = delimIndex + 2;
  226. } else {
  227. // 占位符被转义
  228. argIndex--;
  229. sbuf.append(strPattern, handledPosition, delimIndex - 1);
  230. sbuf.append(C_DELIM_START);
  231. handledPosition = delimIndex + 1;
  232. }
  233. } else {
  234. // 正常占位符
  235. sbuf.append(strPattern, handledPosition, delimIndex);
  236. sbuf.append(ConvertUtils.utf8Str(argArray[argIndex]));
  237. handledPosition = delimIndex + 2;
  238. }
  239. }
  240. }
  241. // 加入最后一个占位符后所有的字符
  242. sbuf.append(strPattern, handledPosition, strPattern.length());
  243. return sbuf.toString();
  244. }
  245. /**
  246. * 下划线转驼峰命名
  247. */
  248. public static String toUnderScoreCase(String str) {
  249. if (str == null) {
  250. return null;
  251. }
  252. StringBuilder sb = new StringBuilder();
  253. // 前置字符是否大写
  254. boolean preCharIsUpperCase = true;
  255. // 当前字符是否大写
  256. boolean curreCharIsUpperCase = true;
  257. // 下一字符是否大写
  258. boolean nexteCharIsUpperCase = true;
  259. for (int i = 0; i < str.length(); i++) {
  260. char c = str.charAt(i);
  261. if (i > 0) {
  262. preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
  263. } else {
  264. preCharIsUpperCase = false;
  265. }
  266. curreCharIsUpperCase = Character.isUpperCase(c);
  267. if (i < (str.length() - 1)) {
  268. nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
  269. }
  270. if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
  271. sb.append(SEPARATOR);
  272. } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
  273. sb.append(SEPARATOR);
  274. }
  275. sb.append(Character.toLowerCase(c));
  276. }
  277. return sb.toString();
  278. }
  279. /**
  280. * 是否包含字符串
  281. *
  282. * @param str 验证字符串
  283. * @param strs 字符串组
  284. * @return 包含返回true
  285. */
  286. public static boolean inStringIgnoreCase(String str, String... strs) {
  287. if (str != null && strs != null) {
  288. for (String s : strs) {
  289. if (str.equalsIgnoreCase(trim(s))) {
  290. return true;
  291. }
  292. }
  293. }
  294. return false;
  295. }
  296. /**
  297. * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
  298. *
  299. * @param name 转换前的下划线大写方式命名的字符串
  300. * @return 转换后的驼峰式命名的字符串
  301. */
  302. public static String convertToCamelCase(String name) {
  303. StringBuilder result = new StringBuilder();
  304. // 快速检查
  305. if (name == null || name.isEmpty()) {
  306. // 没必要转换
  307. return "";
  308. } else if (!name.contains("_")) {
  309. // 不含下划线,仅将首字母大写
  310. return name.substring(0, 1).toUpperCase() + name.substring(1);
  311. }
  312. // 用下划线将原始字符串分割
  313. String[] camels = name.split("_");
  314. for (String camel : camels) {
  315. // 跳过原始字符串中开头、结尾的下换线或双重下划线
  316. if (camel.isEmpty()) {
  317. continue;
  318. }
  319. // 首字母大写
  320. result.append(camel.substring(0, 1).toUpperCase());
  321. result.append(camel.substring(1).toLowerCase());
  322. }
  323. return result.toString();
  324. }
  325. /**
  326. * 驼峰式命名法 例如:user_name->userName
  327. */
  328. public static String toCamelCase(String s) {
  329. if (s == null) {
  330. return null;
  331. }
  332. s = s.toLowerCase();
  333. StringBuilder sb = new StringBuilder(s.length());
  334. boolean upperCase = false;
  335. for (int i = 0; i < s.length(); i++) {
  336. char c = s.charAt(i);
  337. if (c == SEPARATOR) {
  338. upperCase = true;
  339. } else if (upperCase) {
  340. sb.append(Character.toUpperCase(c));
  341. upperCase = false;
  342. } else {
  343. sb.append(c);
  344. }
  345. }
  346. return sb.toString();
  347. }
  348. }

返回类

  1. package com.example.file.common;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class R extends HashMap<String, Object> {
  5. private static final long serialVersionUID = -8157613083634272196L;
  6. public R() {
  7. put("code", 0);
  8. put("msg", "success");
  9. }
  10. public static R error() {
  11. return error(500, "未知异常,请联系管理员");
  12. }
  13. public static R error(String msg) {
  14. return error(500, msg);
  15. }
  16. public static R error(int code, String msg) {
  17. R r = new R();
  18. r.put("code", code);
  19. r.put("msg", msg);
  20. return r;
  21. }
  22. public static R ok(String msg) {
  23. R r = new R();
  24. r.put("msg", msg);
  25. return r;
  26. }
  27. public static R data(Object obj) {
  28. R r = new R();
  29. r.put("data", obj);
  30. return r;
  31. }
  32. public static R ok(Map<String, Object> map) {
  33. R r = new R();
  34. r.putAll(map);
  35. return r;
  36. }
  37. public static R ok() {
  38. return new R();
  39. }
  40. @Override
  41. public R put(String key, Object value) {
  42. super.put(key, value);
  43. return this;
  44. }
  45. }

四、上传下载功能

上传

  1. /**
  2. * 通用上传请求
  3. */
  4. @PostMapping("upload")
  5. public R upload(MultipartFile file){
  6. try {
  7. String filePath = getFilePath();
  8. // 上传并返回新文件名称
  9. String fileName = FileUploadUtils.upload(filePath, file);
  10. String url = dfsConfig.getDomain() + fileName;
  11. return Objects.requireNonNull(R.ok().put("fileName", fileName)).put("url", url);
  12. } catch (Exception e) {
  13. log.error("上传文件失败", e);
  14. return R.error(e.getMessage());
  15. }
  16. }
  17. private String getFilePath() {
  18. // 上传文件路径
  19. String filePath;
  20. String os = System.getProperty("os.name");
  21. if (os.toLowerCase().startsWith("win")) {
  22. //如果是Windows系统
  23. filePath = dfsConfig.getWinPath();
  24. } else {
  25. //linux 和mac
  26. filePath = dfsConfig.getLinuxPath();
  27. }
  28. return filePath;
  29. }

在这里插入图片描述
访问就是在浏览器输入那个url:
在这里插入图片描述

下载

  1. /**
  2. * 通用下载请求
  3. *
  4. * @param fileName 文件名称
  5. * @param delete 是否删除
  6. */
  7. @GetMapping("download")
  8. public void download(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
  9. try {
  10. // 上传文件路径
  11. String filePath = getFilePath();
  12. boolean validFilename = FileUtils.isValidFilename(fileName.trim());
  13. if (!validFilename) {
  14. throw new Exception(StringUtils.strFormat("文件名称({})非法,不允许下载。 ", fileName));
  15. }
  16. String realName = fileName.substring(fileName.lastIndexOf("/") + 1);
  17. String substring = fileName.substring(fileName.lastIndexOf("file-upload/") + 11);
  18. filePath = filePath + substring;
  19. response.setCharacterEncoding("utf-8");
  20. response.setContentType("multipart/form-data");
  21. response.setHeader("Content-Disposition",
  22. "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, System.currentTimeMillis() + realName));
  23. FileUtils.writeBytes(filePath, response.getOutputStream());
  24. if (delete) {
  25. FileUtils.deleteFile(filePath);
  26. }
  27. } catch (Exception e) {
  28. log.error("下载文件失败", e);
  29. }
  30. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,160人围观)

还没有评论,来说两句吧...

相关阅读