aa72ced8 by 蔡永松

Minio服务集成

1 parent 6b9b1868
...@@ -366,7 +366,7 @@ ...@@ -366,7 +366,7 @@
366 </profiles> 366 </profiles>
367 367
368 <properties> 368 <properties>
369 <oracle.version>11.2.0.4</oracle.version> 369 <oracle.version>11.2.0.3</oracle.version>
370 <geotools.version>24-SNAPSHOT</geotools.version> 370 <geotools.version>24-SNAPSHOT</geotools.version>
371 <org.springframework.version>5.1.8.RELEASE</org.springframework.version> 371 <org.springframework.version>5.1.8.RELEASE</org.springframework.version>
372 <org.spring.boot.version>2.1.8.RELEASE</org.spring.boot.version> 372 <org.spring.boot.version>2.1.8.RELEASE</org.spring.boot.version>
......
1 package com.pashanhoo.common.minio;
2
3 import org.springframework.util.StringUtils;
4
5 import java.text.DateFormat;
6 import java.text.ParseException;
7 import java.text.SimpleDateFormat;
8 import java.time.*;
9 import java.util.*;
10
11 /**
12 * @author CAIYONGSONG
13 * @commpany www.pashanhoo.com
14 * @date 2022/7/20
15 */
16 public class DateUtils {
17
18 //获取当天的开始时间
19 public static Date getDayBegin() {
20 Calendar cal = new GregorianCalendar();
21 cal.set(Calendar.HOUR_OF_DAY, 0);
22 cal.set(Calendar.MINUTE, 0);
23 cal.set(Calendar.SECOND, 0);
24 cal.set(Calendar.MILLISECOND, 0);
25 return cal.getTime();
26 }
27 //获取当天的结束时间
28 public static Date getDayEnd() {
29 Calendar cal = new GregorianCalendar();
30 cal.set(Calendar.HOUR_OF_DAY, 23);
31 cal.set(Calendar.MINUTE, 59);
32 cal.set(Calendar.SECOND, 59);
33 return cal.getTime();
34 }
35 //获取昨天的开始时间
36 public static Date getBeginDayOfYesterday() {
37 Calendar cal = new GregorianCalendar();
38 cal.setTime(getDayBegin());
39 cal.add(Calendar.DAY_OF_MONTH, -1);
40 return cal.getTime();
41 }
42 //获取昨天的结束时间
43 public static Date getEndDayOfYesterDay() {
44 Calendar cal = new GregorianCalendar();
45 cal.setTime(getDayEnd());
46 cal.add(Calendar.DAY_OF_MONTH, -1);
47 return cal.getTime();
48 }
49 //获取明天的开始时间
50 public static Date getBeginDayOfTomorrow() {
51 Calendar cal = new GregorianCalendar();
52 cal.setTime(getDayBegin());
53 cal.add(Calendar.DAY_OF_MONTH, 1);
54
55 return cal.getTime();
56 }
57 //获取明天的结束时间
58 public static Date getEndDayOfTomorrow() {
59 Calendar cal = new GregorianCalendar();
60 cal.setTime(getDayEnd());
61 cal.add(Calendar.DAY_OF_MONTH, 1);
62 return cal.getTime();
63 }
64 //获取本周的开始时间
65 @SuppressWarnings("unused")
66 public static Date getBeginDayOfWeek() {
67 Date date = new Date();
68 if (date == null) {
69 return null;
70 }
71 Calendar cal = Calendar.getInstance();
72 cal.setTime(date);
73 int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
74 if (dayofweek == 1) {
75 dayofweek += 7;
76 }
77 cal.add(Calendar.DATE, 2 - dayofweek);
78 return getDayStartTime(cal.getTime());
79 }
80 //获取本周的结束时间
81 public static Date getEndDayOfWeek(){
82 Calendar cal = Calendar.getInstance();
83 cal.setTime(getBeginDayOfWeek());
84 cal.add(Calendar.DAY_OF_WEEK, 6);
85 Date weekEndSta = cal.getTime();
86 return getDayEndTime(weekEndSta);
87 }
88 //获取上周的开始时间
89 @SuppressWarnings("unused")
90 public static Date getBeginDayOfLastWeek() {
91 Date date = new Date();
92 if (date == null) {
93 return null;
94 }
95 Calendar cal = Calendar.getInstance();
96 cal.setTime(date);
97 int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
98 if (dayofweek == 1) {
99 dayofweek += 7;
100 }
101 cal.add(Calendar.DATE, 2 - dayofweek - 7);
102 return getDayStartTime(cal.getTime());
103 }
104 //获取上周的结束时间
105 public static Date getEndDayOfLastWeek(){
106 Calendar cal = Calendar.getInstance();
107 cal.setTime(getBeginDayOfLastWeek());
108 cal.add(Calendar.DAY_OF_WEEK, 6);
109 Date weekEndSta = cal.getTime();
110 return getDayEndTime(weekEndSta);
111 }
112 //获取本月的开始时间
113 public static Date getBeginDayOfMonth() {
114 Calendar calendar = Calendar.getInstance();
115 calendar.set(getNowYear(), getNowMonth() - 1, 1);
116 return getDayStartTime(calendar.getTime());
117 }
118 //获取本月的结束时间
119 public static Date getEndDayOfMonth() {
120 Calendar calendar = Calendar.getInstance();
121 calendar.set(getNowYear(), getNowMonth() - 1, 1);
122 int day = calendar.getActualMaximum(5);
123 calendar.set(getNowYear(), getNowMonth() - 1, day);
124 return getDayEndTime(calendar.getTime());
125 }
126 //获取上月的开始时间
127 public static Date getBeginDayOfLastMonth() {
128 Calendar calendar = Calendar.getInstance();
129 calendar.set(getNowYear(), getNowMonth() - 2, 1);
130 return getDayStartTime(calendar.getTime());
131 }
132 //获取上月的结束时间
133 public static Date getEndDayOfLastMonth() {
134 Calendar calendar = Calendar.getInstance();
135 calendar.set(getNowYear(), getNowMonth() - 2, 1);
136 int day = calendar.getActualMaximum(5);
137 calendar.set(getNowYear(), getNowMonth() - 2, day);
138 return getDayEndTime(calendar.getTime());
139 }
140 //获取本年的开始时间
141 public static Date getBeginDayOfYear() {
142 Calendar cal = Calendar.getInstance();
143 cal.set(Calendar.YEAR, getNowYear());
144 // cal.set
145 cal.set(Calendar.MONTH, Calendar.JANUARY);
146 cal.set(Calendar.DATE, 1);
147
148 return getDayStartTime(cal.getTime());
149 }
150 //获取本年的结束时间
151 public static Date getEndDayOfYear() {
152 Calendar cal = Calendar.getInstance();
153 cal.set(Calendar.YEAR, getNowYear());
154 cal.set(Calendar.MONTH, Calendar.DECEMBER);
155 cal.set(Calendar.DATE, 31);
156 return getDayEndTime(cal.getTime());
157 }
158 //获取某个日期的开始时间
159 public static Date getDayStartTime(Date d) {
160 Calendar calendar = Calendar.getInstance();
161 if(null != d) calendar.setTime(d);
162 calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
163 calendar.set(Calendar.MILLISECOND, 0);
164 return calendar.getTime();
165 }
166 //获取某个日期的结束时间
167 public static Date getDayEndTime(Date d) {
168 Calendar calendar = Calendar.getInstance();
169 if(null != d) calendar.setTime(d);
170 calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
171 calendar.set(Calendar.MILLISECOND, 999);
172 return calendar.getTime();
173 }
174 //获取今年是哪一年
175 public static Integer getNowYear() {
176 Date date = new Date();
177 GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
178 gc.setTime(date);
179 return Integer.valueOf(gc.get(1));
180 }
181 //获取本月是哪一月
182 public static int getNowMonth() {
183 Date date = new Date();
184 GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
185 gc.setTime(date);
186 return gc.get(2) + 1;
187 }
188 //两个日期相减得到的天数
189 public static int getDiffDays(Date beginDate, Date endDate) {
190
191 if (beginDate == null || endDate == null) {
192 throw new IllegalArgumentException("getDiffDays param is null!");
193 }
194
195 long diff = (endDate.getTime() - beginDate.getTime())
196 / (1000 * 60 * 60 * 24);
197
198 int days = new Long(diff).intValue();
199
200 return days;
201 }
202 //两个日期相减得到的毫秒数
203 public static long dateDiff(Date beginDate, Date endDate) {
204 long date1ms = beginDate.getTime();
205 long date2ms = endDate.getTime();
206 return date2ms - date1ms;
207 }
208 //获取两个日期中的最大日期
209 public static Date max(Date beginDate, Date endDate) {
210 if (beginDate == null) {
211 return endDate;
212 }
213 if (endDate == null) {
214 return beginDate;
215 }
216 if (beginDate.after(endDate)) {
217 return beginDate;
218 }
219 return endDate;
220 }
221
222 public static final String DATEFORMAT = "yyyyMMdd";
223 public static final String DATE_FORMAT = "yyyy-MM-dd";
224 public static final String DATA_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
225 /**
226 * 日期转换为"yyyy-MM-dd"格式字符串
227 *
228 * @param date 需要转换的日期
229 * @return String 转换后的日期串
230 */
231 public static String dateToStr(Date date) {
232 DateFormat df = new SimpleDateFormat(DATEFORMAT);
233 return df.format(date);
234 }
235 /**
236 * 日期转换为"yyyy-MM-dd"格式字符串
237 *
238 * @param date 需要转换的日期
239 * @return String 转换后的日期串
240 */
241 public static String dateToString(Date date) {
242 DateFormat df = new SimpleDateFormat(DATE_FORMAT);
243 return df.format(date);
244 }
245
246 /**
247 * 日期转换为"yyyy-MM-dd HH:mm:ss"格式字符串
248 *
249 * @param date
250 * 需要转换的日期
251 * @return 转换后的日期串
252 */
253 public static String dateToStringAll(Date date) {
254 DateFormat df = new SimpleDateFormat(DATA_TIME_FORMAT);
255 return df.format(date);
256 }
257
258 //获取两个日期中的最小日期
259 public static Date min(Date beginDate, Date endDate) {
260 if (beginDate == null) {
261 return endDate;
262 }
263 if (endDate == null) {
264 return beginDate;
265 }
266 if (beginDate.after(endDate)) {
267 return endDate;
268 }
269 return beginDate;
270 }
271 //返回某月该季度的第一个月
272 public static Date getFirstSeasonDate(Date date) {
273 final int[] SEASON = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 };
274 Calendar cal = Calendar.getInstance();
275 cal.setTime(date);
276 int sean = SEASON[cal.get(Calendar.MONTH)];
277 cal.set(Calendar.MONTH, sean * 3 - 3);
278 return cal.getTime();
279 }
280 //返回某个日期下几天的日期
281 public static Date getNextDay(Date date, int i) {
282 Calendar cal = new GregorianCalendar();
283 cal.setTime(date);
284 cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
285 return cal.getTime();
286 }
287 //返回某个日期前几天的日期
288 public static Date getFrontDay(Date date, int i) {
289 Calendar cal = new GregorianCalendar();
290 cal.setTime(date);
291 cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
292 return cal.getTime();
293 }
294 //获取某年某月到某年某月按天的切片日期集合(间隔天数的集合)
295 @SuppressWarnings({ "rawtypes", "unchecked" })
296 public static List getTimeList(int beginYear, int beginMonth, int endYear,
297 int endMonth, int k) {
298 List list = new ArrayList();
299 if (beginYear == endYear) {
300 for (int j = beginMonth; j <= endMonth; j++) {
301 list.add(getTimeList(beginYear, j, k));
302
303 }
304 } else {
305 {
306 for (int j = beginMonth; j < 12; j++) {
307 list.add(getTimeList(beginYear, j, k));
308 }
309
310 for (int i = beginYear + 1; i < endYear; i++) {
311 for (int j = 0; j < 12; j++) {
312 list.add(getTimeList(i, j, k));
313 }
314 }
315 for (int j = 0; j <= endMonth; j++) {
316 list.add(getTimeList(endYear, j, k));
317 }
318 }
319 }
320 return list;
321 }
322 //获取某年某月按天切片日期集合(某个月间隔多少天的日期集合)
323 @SuppressWarnings({ "unchecked", "rawtypes" })
324 public static List getTimeList(int beginYear, int beginMonth, int k) {
325 List list = new ArrayList();
326 Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
327 int max = begincal.getActualMaximum(Calendar.DATE);
328 for (int i = 1; i < max; i = i + k) {
329 list.add(begincal.getTime());
330 begincal.add(Calendar.DATE, k);
331 }
332 begincal = new GregorianCalendar(beginYear, beginMonth, max);
333 list.add(begincal.getTime());
334 return list;
335 }
336 //给当前时间加上min分钟
337 public static Date getNewDate(Date cur,Integer min ) {
338 Calendar c = Calendar.getInstance();
339 c.setTime(cur); //设置时间
340 c.add(Calendar.MINUTE, min); //日期分钟加30,Calendar.DATE(天),Calendar.HOUR(小时)
341 Date date = c.getTime(); //结果
342 return date;
343 }
344
345 /**
346 * 时间格式(yyyy-MM-dd)
347 */
348 public final static String DATE_PATTERN = "yyyy-MM-dd";
349 /**
350 * 时间格式(yyyy-MM-dd HH:mm:ss)
351 */
352 public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
353
354
355
356 /**
357 * 比较两个字符串时间大小
358 */
359 public static int compareTwoTime(String time1, String time2) {
360
361 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
362 "yyyy-MM-dd HH:mm:ss");
363 int flagValue = 0;
364 try {
365 Date date1, date2;
366 date1 = simpleDateFormat.parse(time1);
367 date2 = simpleDateFormat.parse(time2);
368 long millisecond = date1.getTime() - date2.getTime();
369 if (millisecond > 0) {
370 flagValue = 1;
371 } else if (millisecond < 0) {
372 flagValue = -1;
373 } else if (millisecond == 0) {
374 flagValue = 0;
375 }
376 } catch (ParseException e) {
377 e.printStackTrace();
378 }
379 return (flagValue);
380 }
381
382 /**
383 * 比较两个时间差
384 * time1>time2=1
385 * time1<time2=-1
386 * time1=time2=0
387 *
388 * @param time1
389 * @param time2
390 * @return
391 */
392 public static int compareTwoTime(Date time1, Date time2) {
393 int flagValue = 0;
394 try {
395 long millisecond = time1.getTime() - time2.getTime();
396 if (millisecond > 0) {
397 flagValue = 1;
398 } else if (millisecond < 0) {
399 flagValue = -1;
400 } else if (millisecond == 0) {
401 flagValue = 0;
402 }
403 } catch (Exception e) {
404 e.printStackTrace();
405 }
406 return (flagValue);
407 }
408
409 /**
410 * 比较两个时间相差天数
411 */
412 public static float calculateTimeGapDay(String time1, String time2) {
413
414 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
415 "yyyy-MM-dd HH:mm:ss");
416
417 float day = 0;
418 Date date1 = null;
419 Date date2 = null;
420 try {
421 date1 = simpleDateFormat.parse(time1);
422 date2 = simpleDateFormat.parse(time2);
423 long millisecond = date2.getTime() - date1.getTime();
424 day = millisecond / (24 * 60 * 60 * 1000);
425 } catch (ParseException e) {
426 e.printStackTrace();
427 }
428 return (day);
429 }
430
431 /**
432 * 比较两个时间相差天数
433 */
434 public static float calculateTimeGapDay(Date time1, Date time2) {
435 float day = 0;
436 try {
437 Date date1, date2;
438 date1 = time1;
439 date2 = time2;
440 long millisecond = date2.getTime() - date1.getTime();
441 day = millisecond / (24 * 60 * 60 * 1000);
442 } catch (Exception e) {
443 e.printStackTrace();
444 }
445 return (day);
446 }
447
448 /**
449 * 比较两个时间相差小时
450 */
451 public static double calculatetimeGapHour(String time1, String time2) {
452
453 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
454 "yyyy-MM-dd HH:mm:ss");
455 double hour = 0;
456 try {
457 Date date1, date2;
458 date1 = simpleDateFormat.parse(time1);
459 date2 = simpleDateFormat.parse(time2);
460 double millisecond = date2.getTime() - date1.getTime();
461 hour = millisecond / (60 * 60 * 1000);
462 } catch (ParseException e) {
463 e.printStackTrace();
464 }
465 return hour;
466 }
467
468 /**
469 * 比较两个时间相差小时
470 */
471 public static double calculatetimeGapHour(Date date1, Date date2) {
472 double hour = 0;
473 double millisecond = date2.getTime() - date1.getTime();
474 hour = millisecond / (60 * 60 * 1000);
475 return hour;
476 }
477
478 /**
479 * 比较两个时间相差分钟
480 */
481 public static double calculatetimeGapMinute(String time1, String time2) {
482
483 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
484 "yyyy-MM-dd HH:mm:ss");
485 double minute = 0;
486 try {
487 Date date1, date2;
488 date1 = simpleDateFormat.parse(time1);
489 date2 = simpleDateFormat.parse(time2);
490 double millisecond = date2.getTime() - date1.getTime();
491 minute = millisecond / (60 * 1000);
492 } catch (ParseException e) {
493 e.printStackTrace();
494 }
495 return minute;
496 }
497
498 /**
499 * 比较两个时间相差分钟
500 */
501 public static double calculatetimeGapMinute(Date date1, Date date2) {
502 double minute = 0;
503 double millisecond = date2.getTime() - date1.getTime();
504 minute = millisecond / (60 * 1000);
505 return minute;
506 }
507
508 /**
509 * 比较两个时间相差秒
510 */
511 public static double calculatetimeGapSecond(String time1, String time2) {
512 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
513 "yyyy-MM-dd HH:mm:ss");
514 double second = 0;
515 try {
516 Date date1, date2;
517 date1 = simpleDateFormat.parse(time1);
518 date2 = simpleDateFormat.parse(time2);
519 double millisecond = date2.getTime() - date1.getTime();
520 second = millisecond / (1000);
521 } catch (ParseException e) {
522 e.printStackTrace();
523 }
524 return second;
525 }
526
527 /**
528 * 比较两个时间相差秒
529 */
530 public static double calculatetimeGapSecond(Date date1, Date date2) {
531 double second = 0;
532 double millisecond = date2.getTime() - date1.getTime();
533 second = millisecond / (1000);
534 return second;
535 }
536
537 /**
538 * 时间工具
539 *
540 * @param ctime 入参
541 * @return 返回
542 */
543 public static String showTime(Date ctime) {
544 String r = "";
545 if (ctime == null) {
546 return r;
547 }
548 String format = "yyyy-MM-dd HH:mm:ss";
549
550 long nowtimelong = System.currentTimeMillis();
551
552 long ctimelong = ctime.getTime();
553 long result = Math.abs(nowtimelong - ctimelong);
554
555 if (result < 60000) {// 一分钟内
556 long seconds = result / 1000;
557 if (seconds == 0) {
558 r = "刚刚";
559 } else {
560 r = seconds + "秒前";
561 }
562 } else if (result >= 60000 && result < 3600000) {// 一小时内
563 long seconds = result / 60000;
564 r = seconds + "分钟前";
565 } else if (result >= 3600000 && result < 86400000) {// 一天内
566 long seconds = result / 3600000;
567 r = seconds + "小时前";
568 } else if (result >= 86400000 && result < 1702967296) {// 三十天内
569 long seconds = result / 86400000;
570 r = seconds + "天前";
571 } else {// 日期格式
572 SimpleDateFormat df = new SimpleDateFormat(format);
573 r = df.format(ctime);
574 }
575 return r;
576 }
577
578 /**
579 * 根据对应语言-显示对应格式
580 * languageCode:国际语言编码:en zh
581 * date:需处理的日期
582 */
583 public static String formatDateByObject(String languageCode, Object date) {
584 if (StringUtils.isEmpty(languageCode) || date == null || StringUtils.isEmpty(date.toString())) {
585 return "";
586 } else {
587 return DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale(languageCode)).format(date);
588 }
589
590 }
591
592 /**
593 * 根据对应语言-显示对应格式
594 * languageCode:国际语言编码:en zh
595 * date:需处理的日期
596 * 注:通过sql语句查询出来的date不能转换成Date类型来调用此方法 应直接调用用formatDateByObject方法
597 */
598 public static String formatDateByDate(String languageCode, Date date) {
599 if (StringUtils.isEmpty(languageCode) || date == null || StringUtils.isEmpty(date.toString())) {
600 return "";
601 } else {
602 DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale(languageCode));
603 return df.format(date);
604 }
605 }
606
607 /**
608 * 获取当前时间 默认返回 yyyy-MM-dd HH:mm:ss
609 *
610 * @return 当前时间字符串
611 */
612 public static String nowTime(String pattern) {
613 //return new SimpleDateFormat(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern).format(new Date());
614 return localDateTimeToString(LocalDateTime.now(), StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern);
615 }
616
617 /**
618 * 获取当前日期 默认返回 yyyy-MM-dd
619 *
620 * @return 当前日期字符串
621 */
622 public String today(String pattern) {
623 //return new SimpleDateFormat(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern).format(new Date());
624 return localDateToString(LocalDate.now(), StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern);
625 }
626
627 /**
628 * 日期格式化 Date 转 String
629 * 默认返回 yyyy-MM-dd HH:mm:ss
630 *
631 * @param date 日期 必填
632 * @param pattern 转换格式
633 * @return 返回格式后日期
634 */
635 public static String dateToString(Date date, String pattern) {
636 if (date == null) {
637 return null;
638 } else {
639 return new SimpleDateFormat(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern).format(date);
640 }
641 }
642
643
644 /**
645 * String 转 LocalDate
646 *
647 * @param date 待转换的字符串 必填
648 * @param pattern 转换格式 默认为yyyy-MM-dd
649 * @return
650 */
651 public static LocalDate stringToLocalDate(String date, String pattern) {
652 if (StringUtils.isEmpty(date)) {
653 return null;
654 } else {
655 return LocalDate.parse(date, java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern));
656 }
657 }
658
659 /**
660 * String 转 LocalDateTime
661 *
662 * @param date 待转换的字符串 必填
663 * @param pattern 转换格式 默认为yyyy-MM-dd HH:mm:ss
664 * @return
665 */
666 public static LocalDateTime stringToLocalDateTime(String date, String pattern) {
667 if (StringUtils.isEmpty(date)) {
668 return null;
669 } else {
670 return LocalDateTime.parse(date, java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern));
671 }
672 }
673
674 /**
675 * String 转 LocalTime
676 *
677 * @param date 待转换的字符串 必填
678 * @param pattern 转换格式 默认为HH:mm:ss
679 * @return
680 */
681 public static LocalTime stringToLocalTime(String date, String pattern) {
682 if (StringUtils.isEmpty(date)) {
683 return null;
684 } else {
685 return LocalTime.parse(date, java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "HH:mm:ss" : pattern));
686 }
687 }
688
689 /**
690 * LocalDate 转 String
691 *
692 * @param localDate
693 * @param pattern
694 * @return
695 */
696 public static String localDateToString(LocalDate localDate, String pattern) {
697 return localDate.format(java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern));
698 }
699
700 /**
701 * LocalDateTime 转 String
702 *
703 * @param localDateTime
704 * @param pattern
705 * @return
706 */
707 public static String localDateTimeToString(LocalDateTime localDateTime, String pattern) {
708 return localDateTime.format(java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern));
709 }
710
711 /**
712 * LocalTime 转 String
713 *
714 * @param localTime
715 * @param pattern
716 * @return
717 */
718 public static String localTimeToString(LocalTime localTime, String pattern) {
719 return localTime.format(java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "HH:mm:ss" : pattern));
720 }
721
722 /**
723 * LocalDate 转 Date
724 *
725 * @param localDate
726 * @return
727 */
728 public static Date localDateToDate(LocalDate localDate) {
729 ZoneId zoneId = ZoneId.systemDefault();
730 ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
731 return Date.from(zdt.toInstant());
732 }
733
734 /**
735 * LocalDateTime 转 Date
736 *
737 * @param localDateTime
738 * @return
739 */
740 public static Date localDateTimeToDate(LocalDateTime localDateTime) {
741 ZoneId zoneId = ZoneId.systemDefault();
742 ZonedDateTime zdt = localDateTime.atZone(zoneId);
743 return Date.from(zdt.toInstant());
744 }
745
746 /**
747 * LocalDateTime 转 LocalDate
748 *
749 * @param localDateTime
750 * @return
751 */
752 public static LocalDate localDateTimeToLocalDate(LocalDateTime localDateTime) {
753 return localDateTime.toLocalDate();
754 }
755
756 /**
757 * LocalDateTime 转 LocalTime
758 *
759 * @param localDateTime
760 * @return
761 */
762 public static LocalTime localDateTimeToLocalTime(LocalDateTime localDateTime) {
763 return localDateTime.toLocalTime();
764 }
765
766 /**
767 * Date 转 LocalDate
768 * atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
769 *
770 * @param date
771 * @return
772 */
773 public static LocalDate dateToLocalDate(Date date) {
774 Instant instant = date.toInstant();
775 ZoneId zoneId = ZoneId.systemDefault();
776 return instant.atZone(zoneId).toLocalDate();
777 }
778
779 /**
780 * 将 Date 转 LocalDateTime
781 * atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
782 *
783 * @param date
784 * @return
785 */
786 public static LocalDateTime dateToLocalDateTime(Date date) {
787 Instant instant = date.toInstant();
788 ZoneId zoneId = ZoneId.systemDefault();
789 return instant.atZone(zoneId).toLocalDateTime();
790 }
791
792 /**
793 * 将 Date 转 LocalTime
794 * atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
795 *
796 * @param date
797 * @return
798 */
799 public static LocalTime dateToLocalTime(Date date) {
800 Instant instant = date.toInstant();
801 ZoneId zoneId = ZoneId.systemDefault();
802 return instant.atZone(zoneId).toLocalTime();
803 }
804
805 /**
806 * 计算两个LocalDateTime yyyy-MM-dd HH:mm:ss 之间的 时间间隔
807 *
808 * @param localDateTime1
809 * @param localDateTime2
810 * @return Map<String, Object>
811 * millis:毫秒差
812 * seconds:秒差
813 * minutes:分钟差
814 * hours:小时差
815 * days:天数差
816 * weeks:周差
817 * months:月份差
818 * quarters:季度差
819 * years:年份差
820 */
821 public static Map<String, Object> minusToLocalDateTime(LocalDateTime localDateTime1, LocalDateTime localDateTime2) {
822 Duration duration = Duration.between(localDateTime1, localDateTime2);
823 Map<String, Object> map = new HashMap<>(16);
824 //毫秒差
825 map.put("millis", duration.toMillis());
826 //秒差
827 map.put("seconds", duration.toMillis() / 1000);
828 //分钟差
829 map.put("minutes", duration.toMinutes());
830 //小时差
831 map.put("hours", duration.toHours());
832 //天数差
833 map.put("days", duration.toDays());
834 //周差
835 map.put("weeks", duration.toDays() / 7);
836 Map<String, Object> map1 = minusToLocalDate(localDateTime1.toLocalDate(), localDateTime2.toLocalDate());
837 //季度差
838 map.put("quarters", map1.get("quarters"));
839 //月份差
840 map.put("months", map1.get("months"));
841 //年份差
842 map.put("years", map1.get("years"));
843 return map;
844 }
845
846 /**
847 * 计算两个LocalTime HH:mm:ss 之间的 时间间隔
848 *
849 * @param localTime1
850 * @param localTime2
851 * @return Map<String, Object>
852 * millis:毫秒差
853 * seconds:秒差
854 * minutes:分钟差
855 * hours:小时差
856 */
857 public static Map<String, Object> minusToLocalTime(LocalTime localTime1, LocalTime localTime2) {
858 Duration duration = Duration.between(localTime1, localTime2);
859 Map<String, Object> map = new HashMap<>(16);
860 //毫秒差
861 map.put("millis", duration.toMillis());
862 //秒差
863 map.put("seconds", duration.toMillis() / 1000);
864 //分钟差
865 map.put("minutes", duration.toMinutes());
866 //小时差
867 map.put("hours", duration.toHours());
868 return map;
869 }
870
871 /**
872 * 计算两个LocalDate yyyy-MM-dd 之间的 时间间隔
873 *
874 * @param localDate1
875 * @param localDate2
876 * @return Map<String, Object>
877 * days:天数差
878 * weeks:周差
879 * months:月份差
880 * quarters:季度差
881 * years:年份差
882 */
883 public static Map<String, Object> minusToLocalDate(LocalDate localDate1, LocalDate localDate2) {
884 Period period = localDate1.until(localDate2);
885 Map<String, Object> map = new HashMap<>(16);
886 //天数差
887 map.put("days", period.getDays());
888 //周差
889 map.put("weeks", period.getDays() / 7);
890 //月份差
891 map.put("months", period.getMonths());
892 // 季度差
893 map.put("quarters", period.getMonths() / 3);
894 //年份差
895 map.put("years", period.getYears());
896 return map;
897 }
898
899 /**
900 * 根据时间 和时间格式 校验是否正确
901 * 示例:
902 * String date = "2020-01-25 12:36:45";
903 * 传入date的长度、data、"yyyy-MM-dd HH:mm:ss" = true 《或者》 传入date的长度、data、"yyyy-MM-dd" = false
904 * @param length 校验的长度
905 * @param sDate 校验的日期
906 * @param format 校验的格式
907 * @return
908 */
909 public static boolean isLegalDate(int length, String sDate,String format) {
910 int legalLen = length;
911 if ((sDate == null) || (sDate.length() != legalLen)) {
912 return false;
913 }
914 DateFormat formatter = new SimpleDateFormat(format);
915 try {
916 Date date = formatter.parse(sDate);
917 return sDate.equals(formatter.format(date));
918 } catch (Exception e) {
919 return false;
920 }
921 }
922 }
923
1 package com.pashanhoo.common.minio;
2
3 import io.minio.*;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.stereotype.Component;
8 import org.springframework.web.multipart.MultipartFile;
9
10 import java.io.ByteArrayInputStream;
11 import java.io.InputStream;
12 import java.util.Date;
13
14 /**
15 * @author CAIYONGSONG
16 * @commpany www.pashanhoo.com
17 * @date 2022/7/20
18 */
19 @Component
20 public class FileServerOptUtil {
21 private Logger log = LoggerFactory.getLogger(FileServerOptUtil.class);
22
23 @Autowired
24 MinioClient minioClient;
25
26 /**
27 * 获取桶中某个对象的输入流
28 * @param bucketName
29 * @param path
30 * @return
31 */
32 public InputStream getObjectInputStream(String bucketName, String path){
33 log.info("从桶:" + bucketName + ",获取:" + path + "对象流!");
34 InputStream stream = null;
35 try {
36 stream = minioClient.getObject(
37 GetObjectArgs.builder().bucket(bucketName).object(path).build());
38 } catch (Exception e) {
39 log.error("从桶:" + bucketName + ",获取:" + path + "对象流错误!");
40 e.printStackTrace();
41 }
42 return stream;
43 }
44
45 /**
46 *
47 * @param bucketName
48 * @param dirPath 如:path/to/
49 * @return
50 */
51 public boolean mkdir(String bucketName,String dirPath){
52 log.info("在桶:" + bucketName + ",中创建:" + dirPath);
53 boolean result = false;
54 try {
55 minioClient.putObject(
56 PutObjectArgs.builder().bucket(bucketName).object(dirPath).stream(
57 new ByteArrayInputStream(new byte[] {}), 0, -1)
58 .build());
59 result = true;
60 } catch (Exception e) {
61 log.error("在桶:" + bucketName + ",中创建:" + dirPath + "错误!");
62 e.printStackTrace();
63 }
64 return result;
65 }
66
67
68 /**
69 * 往对象存储服务目标桶的目标位置上传文件
70 * @param bucketName 桶
71 * @param toPath 目标位置如:test/2.txt
72 * @param fromPath 本地文件位置
73 * @return
74 */
75 public boolean uploadObject(String bucketName,String toPath,String fromPath ){
76 log.info("从本地:" + fromPath + "往桶:" + bucketName + ",中上传文件:" + toPath);
77 boolean result = false;
78 try {
79 minioClient.uploadObject(
80 UploadObjectArgs.builder()
81 .bucket(bucketName)
82 .object(toPath)
83 .filename(fromPath)
84 .build());
85 result = true;
86 } catch (Exception e) {
87 log.error("从本地:" + fromPath + "往桶:" + bucketName + ",中上传文件:" + toPath + "错误!");
88 e.printStackTrace();
89 }
90 return result;
91 }
92
93
94 /**
95 * 从桶中下载文件到本地文件
96 * @param bucketName
97 * @param fromPath
98 * @param toPath
99 * @return
100 */
101 public boolean downloadFile(String bucketName,String fromPath,String toPath){
102 log.info("从桶:" + bucketName + "中将" + fromPath + "文件下载到:" + toPath);
103 boolean result = false;
104 try {
105 minioClient.downloadObject(
106 DownloadObjectArgs.builder()
107 .bucket(bucketName)
108 .object(fromPath)
109 .filename(toPath)
110 .build());
111 result = true;
112 } catch (Exception e) {
113 log.error("从桶:" + bucketName + "中将" + fromPath + "文件下载到:" + toPath + "错误!");
114 e.printStackTrace();
115 }
116 return result;
117 }
118 public static String extractFilename(MultipartFile file){
119 if (file.isEmpty()) {
120 throw new RuntimeException("文件不存在!");
121 }
122 return DateUtils.dateToStr(new Date()) + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename() ;
123
124 }
125 }
...\ No newline at end of file ...\ No newline at end of file
1 package com.pashanhoo.common.minio;
2
3 import io.minio.MinioClient;
4 import lombok.Data;
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7 import org.springframework.boot.context.properties.ConfigurationProperties;
8 import org.springframework.context.annotation.Bean;
9 import org.springframework.stereotype.Component;
10
11 /**
12 * @author CAIYONGSONG
13 * @commpany www.pashanhoo.com
14 * @date 2022/7/20
15 */
16 @Data
17 @Component
18 @ConfigurationProperties(prefix = "minio")
19 public class MinioConfig {
20 private Logger log = LoggerFactory.getLogger(MinioConfig.class);
21
22 // minio地址
23 private String minioUrl;
24 //minio账号
25 private String accessKey;
26 //minio密码
27 private String secretKey;
28 //存储桶名称 */
29 public String bucketName;
30 // "如果是true,则用的是https而不是http,默认值是true"
31 public static Boolean secure = false;
32
33
34 @Bean
35 public MinioClient getMinioClient(){
36 log.info("初始化MinioClient客户端:minioUrl:" + minioUrl + ",accessKey:" + accessKey + ",secretKey:" + secretKey);
37 MinioClient minioClient = MinioClient.builder()
38 .endpoint(minioUrl)
39 .credentials(accessKey,secretKey)
40 .build();
41 return minioClient;
42 }
43
44 }
1 package com.pashanhoo.common.minio;
2
3 import io.minio.*;
4 import io.minio.messages.DeleteError;
5 import io.minio.messages.DeleteObject;
6 import io.minio.messages.Item;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.stereotype.Component;
9 import org.springframework.util.FastByteArrayOutputStream;
10 import org.springframework.web.multipart.MultipartFile;
11
12 import javax.servlet.ServletOutputStream;
13 import javax.servlet.http.HttpServletResponse;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.stream.Collectors;
17
18 /**
19 * @author CAIYONGSONG
20 * @commpany www.pashanhoo.com
21 * @date 2022/7/20
22 */
23
24 @Component
25 public class MinioUtil {
26
27 @Autowired
28 private MinioClient minioClient;
29
30 /**
31 * 查看存储bucket是否存在
32 *
33 * @param bucketName 存储bucket
34 * @return boolean
35 */
36 public Boolean bucketExists(String bucketName) {
37 Boolean found;
38 try {
39 found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
40 } catch (Exception e) {
41 e.printStackTrace();
42 return false;
43 }
44 return found;
45 }
46
47 /**
48 * 创建存储bucket
49 *
50 * @param bucketName 存储bucket名称
51 * @return Boolean
52 */
53 public Boolean makeBucket(String bucketName) {
54 try {
55 minioClient.makeBucket(MakeBucketArgs.builder()
56 .bucket(bucketName)
57 .build());
58 } catch (Exception e) {
59 e.printStackTrace();
60 return false;
61 }
62 return true;
63 }
64
65 /**
66 * 删除存储bucket
67 *
68 * @param bucketName 存储bucket名称
69 * @return Boolean
70 */
71 public Boolean removeBucket(String bucketName) {
72 try {
73 minioClient.removeBucket(RemoveBucketArgs.builder()
74 .bucket(bucketName)
75 .build());
76 } catch (Exception e) {
77 e.printStackTrace();
78 return false;
79 }
80 return true;
81 }
82
83 /**
84 * 文件上传
85 *
86 * @param file 文件
87 * @param bucketName 存储bucket
88 * @return Boolean
89 */
90 public Boolean upload(MultipartFile file, String fileName, String bucketName) {
91 try {
92 PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName)
93 .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
94 //文件名称相同会覆盖
95 minioClient.putObject(objectArgs);
96 } catch (Exception e) {
97 e.printStackTrace();
98 return false;
99 }
100 return true;
101 }
102
103 /**
104 * 文件下载
105 *
106 * @param bucketName 存储bucket名称
107 * @param fileName 文件名称
108 * @param res response
109 * @return Boolean
110 */
111 public void download(String bucketName, String fileName, HttpServletResponse res) {
112 GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
113 .object(fileName).build();
114 try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
115 byte[] buf = new byte[1024];
116 int len;
117 try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
118 while ((len = response.read(buf)) != -1) {
119 os.write(buf, 0, len);
120 }
121 os.flush();
122 byte[] bytes = os.toByteArray();
123 res.setCharacterEncoding("utf-8");
124 //设置强制下载不打开
125 res.setContentType("application/force-download");
126 res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
127 try (ServletOutputStream stream = res.getOutputStream()) {
128 stream.write(bytes);
129 stream.flush();
130 }
131 }
132 } catch (Exception e) {
133 e.printStackTrace();
134 }
135 }
136
137 /**
138 * 查看文件对象
139 *
140 * @param bucketName 存储bucket名称
141 * @return 存储bucket内文件对象信息
142 */
143 public List<ObjectItem> listObjects(String bucketName) {
144 Iterable<Result<Item>> results = minioClient.listObjects(
145 ListObjectsArgs.builder().bucket(bucketName).build());
146 List<ObjectItem> objectItems = new ArrayList<>();
147 try {
148 for (Result<Item> result : results) {
149 Item item = result.get();
150 ObjectItem objectItem = new ObjectItem();
151 objectItem.setObjectName(item.objectName());
152 objectItem.setSize(item.size());
153 objectItems.add(objectItem);
154 }
155 } catch (Exception e) {
156 e.printStackTrace();
157 return null;
158 }
159 return objectItems;
160 }
161
162 /**
163 * 批量删除文件对象
164 *
165 * @param bucketName 存储bucket名称
166 * @param objects 对象名称集合
167 */
168 public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
169 List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
170 Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
171 return results;
172 }
173
174 }
1 package com.pashanhoo.common.minio;
2
3 import io.swagger.annotations.ApiModel;
4
5 /**
6 * @author CAIYONGSONG
7 * @commpany www.pashanhoo.com
8 * @date 2022/7/20
9 */
10 @ApiModel("用户实体类")
11 public class ObjectItem {
12
13 long size;
14 String objectName;
15
16 public long getSize() {
17 return size;
18 }
19
20 public void setSize(long size) {
21 this.size = size;
22 }
23
24 public String getObjectName() {
25 return objectName;
26 }
27
28 public void setObjectName(String objectName) {
29 this.objectName = objectName;
30 }
31 }
1 package com.pashanhoo.config;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.springframework.context.annotation.Bean;
5 import org.springframework.context.annotation.Configuration;
6 import org.springframework.web.client.RestTemplate;
7
8 /**
9 * @author CAIYONGSONG
10 * @commpany www.pashanhoo.com
11 * @date 2022/8/18
12 */
13 @Configuration
14 @Slf4j
15 public class TestTemplateBeanConfig {
16 @Bean
17 RestTemplate restTemplate(){
18 log.info("完成初始化RestTemplate得bean");
19 return new RestTemplate();
20 }
21 }
1 package com.pashanhoo.qys.controller;
2
3
4 import com.pashanhoo.common.Result;
5 import com.pashanhoo.qys.service.SysFileService;
6 import io.minio.GetObjectArgs;
7 import io.minio.ListObjectsArgs;
8 import io.minio.MinioClient;
9 import io.minio.messages.Item;
10 import io.swagger.annotations.Api;
11 import io.swagger.annotations.ApiOperation;
12 import org.apache.tomcat.util.http.fileupload.IOUtils;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.http.MediaType;
15 import org.springframework.util.StringUtils;
16 import org.springframework.web.bind.annotation.*;
17 import org.springframework.web.multipart.MultipartFile;
18
19 import javax.servlet.http.HttpServletResponse;
20 import java.io.BufferedOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.URLEncoder;
24
25 /**
26 * @author CAIYONGSONG
27 * @commpany www.pashanhoo.com
28 * @date 2022/7/20
29 */
30
31 @Api(tags = "Minio文件上传")
32 @RestController
33 @RequestMapping("/system/file")
34 public class SysFileController {
35
36 @Autowired
37 private SysFileService sysFileService;
38
39 @Autowired
40 private MinioClient minioClient;
41
42 /**
43 * 图片上传minio
44 *
45 * @param file 图片文件
46 * @return 返回
47 */
48 @ApiOperation("点选文件-文件上传")
49 @RequestMapping(value = "/upload", method = RequestMethod.POST)
50 public Result uploadFileMinio(MultipartFile file) {
51 String url = sysFileService.uploadFileMinio(file);
52 if (!StringUtils.isEmpty(url)) {
53 return Result.ok(url);
54 }
55 return Result.error(-1,"上传失败");
56 }
57
58 @PostMapping(value = "/upload-files" )
59 @ApiOperation(value = "文件上传(支持批量)", notes = "文件上传(支持批量)")
60 public Result uploadFiles(@RequestPart MultipartFile[] files ) throws IOException {
61 String url = sysFileService.uploadFileMinio(files);
62 if (!StringUtils.isEmpty(url)) {
63 return Result.ok(url);
64 }
65 return Result.error(-1,"上传失败");
66 }
67
68 // 暂未实现
69 @ApiOperation("文件下载")
70 @RequestMapping(value = "/download", method = RequestMethod.POST)
71 public String download(HttpServletResponse response) {
72 try {
73 Iterable<io.minio.Result<Item>> results = minioClient.listObjects(
74 ListObjectsArgs.builder().bucket("eci-bucket").build()//获取bucket里所有文件信息
75 );
76 String fileName = null;
77 for (io.minio.Result<Item> result : results) {
78 Item item = result.get();
79 fileName = item.objectName();
80 System.out.println(item.lastModified() + "\t" + item.size() + "\t" + item.objectName());
81 }
82
83 InputStream object = minioClient.getObject(GetObjectArgs.builder().bucket("eci-bucket").object(fileName).build());
84 BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
85 IOUtils.copy(object, bos);
86 response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
87 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
88 bos.flush();
89 return "success";
90 } catch (Exception e) {
91 e.printStackTrace();
92 return e.getMessage();
93 }
94 }
95
96 }
...\ No newline at end of file ...\ No newline at end of file
1 package com.pashanhoo.qys.service;
2
3 import org.springframework.web.multipart.MultipartFile;
4
5 /**
6 * @author CAIYONGSONG
7 * @commpany www.pashanhoo.com
8 * @date 2022/7/20
9 */
10 public interface SysFileService {
11
12 public String uploadFileMinio(MultipartFile file);
13 public String uploadFileMinio(MultipartFile[] file);
14 }
1 package com.pashanhoo.qys.service.impl;
2
3 import com.pashanhoo.common.minio.FileServerOptUtil;
4 import com.pashanhoo.common.minio.MinioConfig;
5 import com.pashanhoo.common.minio.MinioUtil;
6 import com.pashanhoo.qys.service.SysFileService;
7 import lombok.extern.slf4j.Slf4j;
8 import org.springframework.beans.factory.annotation.Autowired;
9 import org.springframework.stereotype.Service;
10 import org.springframework.web.multipart.MultipartFile;
11
12 /**
13 * @author CAIYONGSONG
14 * @commpany www.pashanhoo.com
15 * @date 2022/7/20
16 */
17 @Service
18 @Slf4j
19 public class SysFileServiceImpl implements SysFileService {
20
21 @Autowired
22 private MinioConfig minioConfig;
23
24 @Autowired
25 private MinioUtil minioUtil;
26
27 @Override
28 public String uploadFileMinio(MultipartFile[] files){
29 Long st = System.currentTimeMillis();
30 log.info("开始上传批量文件" + files.length);
31 // 判断存储桶是否存在
32 if (!minioUtil.bucketExists(minioConfig.getBucketName())) {
33 minioUtil.makeBucket(minioConfig.getBucketName());
34 }
35 StringBuilder sbf = new StringBuilder();
36 for (MultipartFile file : files) {
37 if (file.isEmpty()) {
38 throw new RuntimeException("文件不存在!");
39 }
40 log.info("循环开始上传单个文件,文件大小:" + file.getSize());
41
42 // 生成文件名 按照要求-带文件夹路径的文件的全路径
43 String fineName = FileServerOptUtil.extractFilename(file);
44 try {
45 // 上传文件
46 minioUtil.upload(file, fineName, minioConfig.getBucketName());
47 } catch (Exception e) {
48 System.out.println("上传minio服务器期出错了 " + e.getMessage());
49 e.printStackTrace();
50 return null;
51 }
52 sbf.append(minioConfig.getMinioUrl()).append("/").append( minioConfig.getBucketName())
53 .append("/").append(fineName).append(",");
54 }
55 //String url = minioConfig.getMinioUrl() + "/" + minioConfig.getBucketName() + "/" + fineName;
56 String resUrl = sbf.toString().substring(0,(sbf.length()-1));
57 log.info("上传文件结束,总耗时:"+(System.currentTimeMillis() - st) +"s, 文件路径:" + resUrl );
58 return resUrl;
59
60 }
61
62 @Override
63 public String uploadFileMinio(MultipartFile file) {
64 Long st = System.currentTimeMillis();
65 if (file.isEmpty()) {
66 throw new RuntimeException("文件不存在!");
67 }
68 log.info("开始上传单个文件,文件大小:" + (file.getSize()/1024) + "KB");
69 // 判断存储桶是否存在
70 if (!minioUtil.bucketExists(minioConfig.getBucketName())) {
71 minioUtil.makeBucket(minioConfig.getBucketName());
72 }
73 // 生成文件名 按照要求-带文件夹路径的文件的全路径
74 String fineName = FileServerOptUtil.extractFilename(file);
75 try {
76 // 上传文件
77 minioUtil.upload(file, fineName, minioConfig.getBucketName());
78 } catch (Exception e) {
79 System.out.println("上传minio服务器期出错了 " + e.getMessage());
80 e.printStackTrace();
81 return null;
82 }
83
84 String url = minioConfig.getMinioUrl() + "/" + minioConfig.getBucketName() + "/" + fineName;
85
86 log.info("上传文件结束,总耗时:"+(System.currentTimeMillis() - st) +"ms, 文件路径:" + url );
87 return url;
88
89 }
90 }
...\ No newline at end of file ...\ No newline at end of file
...@@ -7,8 +7,8 @@ server: ...@@ -7,8 +7,8 @@ server:
7 spring: 7 spring:
8 servlet: 8 servlet:
9 multipart: 9 multipart:
10 maxFileSize: 10MB 10 maxFileSize: 100MB
11 maxRequestSize: 10MB 11 maxRequestSize: 500MB
12 application: 12 application:
13 name: hzbdcsyn 13 name: hzbdcsyn
14 jackson: 14 jackson:
...@@ -71,5 +71,16 @@ management: ...@@ -71,5 +71,16 @@ management:
71 71
72 logging: 72 logging:
73 config: "classpath:logback-spring.xml" 73 config: "classpath:logback-spring.xml"
74 74 # Minio配置
75 minio:
76 # minio配置的地址,端口9000
77 minioUrl: http://172.16.56.30:90
78 # 账号
79 accessKey: minioadmin
80 # 密码
81 secretKey: minioadmin
82 # MinIO桶名字
83 bucketName: ecibucket
84 swagger2:
85 enable: false
75 86
......
...@@ -7,8 +7,8 @@ server: ...@@ -7,8 +7,8 @@ server:
7 spring: 7 spring:
8 servlet: 8 servlet:
9 multipart: 9 multipart:
10 maxFileSize: 10MB 10 maxFileSize: 100MB
11 maxRequestSize: 10MB 11 maxRequestSize: 500MB
12 application: 12 application:
13 name: hzbdcsyn 13 name: hzbdcsyn
14 jackson: 14 jackson:
...@@ -71,5 +71,16 @@ management: ...@@ -71,5 +71,16 @@ management:
71 71
72 logging: 72 logging:
73 config: "classpath:logback-spring.xml" 73 config: "classpath:logback-spring.xml"
74 74 # Minio配置
75 minio:
76 # minio配置的地址,端口9000
77 minioUrl: http://172.16.56.30:90
78 # 账号
79 accessKey: minioadmin
80 # 密码
81 secretKey: minioadmin
82 # MinIO桶名字
83 bucketName: ecibucket
84 swagger2:
85 enable: true
75 86
......
1 spring: 1 spring:
2 profiles: 2 profiles:
3 active: dev 3 active: test
......